容器网络入门操作2
https://hub.docker.com/_/nginx
测试2:
拉取一个nginx镜像文件,这里使用的是最小化的版本
docker pull nginx:alpine
然后启动nginx容器:
docker run --name nginx1 -d --net bridge nginx:alpine然后通过docker inspect查看nginx1这个容器的ip地址:
root@09-1:/data/mysql3# docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' nginx1
172.17.0.3在宿主机上使用 curl 172.17.0.3 即可访问nginx容器的主页:
root@09-1:/data/mysql3# curl 172.17.0.3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>但是这个nginx在宿主机以外是无法访问的,关于docker内置支持的四种网络类型,可以参考这张图:

所以,要实现跨宿主机的网络访问,首先要把容器的端口暴露在宿主机的网络接口上,原理与路由器上的NAT类似。通过增加参数 -p [宿主端口]:[容器端口] 实现,例如:
docker ps现在可以看到端口转发的情况:
也可以使用docker port查看:
使用iptables -t nat -vnL可以看到对应的NAT规则:
这样,通过其他主机,访问这台宿主机的http://ip:10080端口,就能访问到nginx2容器内的80端口,获取nginx主页信息。
Last updated
Was this helpful?