037、外部网络如何访问容器 (2019-02-26 周二)
外部访问容器的方法:端口映射
动态映射 -p 80 将容器的 tcp 80 端口映射到dockerhost的一个动态端口上
静态映射 -p 80:80 将容器的 tcp 80 端口映射到docker host的一个tcp80端口上
出容器使用的是 NAT ,进容器使用的是端口映射docker-proxy
root@docker-lab:~# docker run -d -p 80 httpd # 将容器的80口映射到docker host的一个随机端口
3f65c28de842fded2a32a9c98afdefd289fc9013b4cf537236bdaee12ec8d87a
root@docker-lab:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3f65c28de842 httpd "httpd-foreground" 9 seconds ago Up 7 seconds 0.0.0.0:32768->80/tcp quizzical_morse
root@docker-lab:~# docker run -d -p 80:80 nginx # 将容器的80口映射到docker host的80口
a7e821d05e1d68c9db005db7d38c932234e7b06fcf38ec973dde0870207bae87
root@docker-lab:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a7e821d05e1d nginx "nginx -g 'daemon of…" 4 seconds ago Up 3 seconds 0.0.0.0:80->80/tcp quizzical_banach
3f65c28de842 httpd "httpd-foreground" 34 seconds ago Up 32 seconds 0.0.0.0:32768->80/tcp quizzical_morse
root@docker-lab:~# curl http://127.0.0.1:80 # 在容器外面访问docker host IP:80 验证
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
</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>
root@docker-lab:~# curl http://127.0.0.1:32768 # 在容器外面访问docker host IP:32768 验证
<html><body><h1>It works!</h1></body></html>
root@docker-lab:~# ps -ef | grep proxy # docker host 上提供端口映射服务的是 docker-proxy 进程
root 31150 24323 0 09:02 ? 00:00:00 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 32768 -container-ip 172.17.0.2 -container-port 80
root 31465 24323 0 09:02 ? 00:00:00 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 80 -container-ip 172.17.0.3 -container-port 80
end