本文轉自https://www.freeaihub.com/article/container-module-in-docker-network.html,該頁可在線運行案例
在前一篇Docker 網絡:host模式中我們已經介紹Docker網絡模型中的host模式。本節將對Docker網絡模型中的host模型進行理論介紹,再通過案例的實操,讓您更好地去理解docker網絡中的container模式。
container模式
Docker網絡container模式是指,創建新容器的時候,通過--net container
參數,指定其和已經存在的某個容器共享一個 Network Namespace。如下圖所示,右方黃色新創建的container,其網卡共享左邊容器。因此就不會擁有自己獨立的 IP,而是共享左邊容器的 IP 172.17.0.2,端口范圍等網絡資源,兩個容器的進程通過 lo 網卡設備通信。
但這兩個容器在其他的資源上,如文件系統、進程列表等還是隔離的。
container模式實例
使用busybox鏡像新建bb容器,bb容器網絡模型默認采用的bridge模式,我們稍后會講。
docker run -itd --name bb -p busybox
使用Nginx鏡像新建nginx容器,並用--net container:bb
參數,指定該容器的網絡模型為container模式,和bb容器共用相同的網絡命名空間。
docker load < /share/images/nginx.tar
docker run -d --name nginx --net container:bb nginx
進入bb容器
docker exec -it bb sh
使用命令查看網絡端口情況
netstat -antp
我們會得到這樣的返回,我們已經看到,nginx容器的80端口已經映射到了bb容器的80端口
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN -
在bb容器內部訪問bb容器本機的80商品,我們可以看到實際上可以訪問到nginx容器的
wget -O- localhost
查看bb容器的ip地址,並退出bb容器
ifconfig
exit
使用上面得到IP地址,從雲環境主機的環境,去訪問
curl 172.17.0.2
也會得到
<!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>
總結
Docker container網絡模式,這種模式可以節約一定的網絡資源,並能降低容器間的通信的難度。container網絡模式使多個容器共享網絡環境,在這種模式下容器可以通過訪問localhost來訪問 namespace下的其他容器,網絡性能高。