docker的网络模式分为桥接模式、
桥接模式(bridge)

创建两个容器
1 2
| sudo docker run -d -P --rm --name centos_net1 --net bridge centos ping 127.0.0.1 sudo docker run -d -P --rm --name centos_net2 --net bridge centos ping 127.0.0.1
|

此时无论用centos_net1 ping centos_net2还是centos_net2 ping centos_net1都ping不通
将centos_net2删除,重新创建centos_net2,创建时使用–link选项关联centos_net1
此时,centos_net2可以ping centos_net1,但是centos_net1不能ping centos_net2。

实现原理:
通过查看centos_net2的hosts文件发现,这是通过在centos_net2的hosts文件中添加centos_net1的ip地址实现的。

主机模式(host)

none

container

自定义模式
通过sudo docker network create -d brige --subnet 192.168.111.2/24 --gateway 192.168.111.0 mynet
创建网络
使用sudo docker network inspect mynet
可以查看刚刚创建的网络
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| [ { "Name": "mynet", "Id": "c47f0ad4d28636df8aad2203f28ad8bb969d49beddd754fdeeeb4b0727ac9204", "Created": "2023-11-20T10:09:00.993237988+08:00", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": {}, "Config": [ { "Subnet": "192.168.111.2/24", "Gateway": "192.168.111.3" } ] }, "Internal": false, "Attachable": false, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": {}, "Options": {}, "Labels": {} } ]
|
创建两个容器
1 2
| sudo docker run --name centos_net1 -d -P --net mynet --rm centos ping 127.0.0.1 sudo docker run --name centos_net2 -d -P --net mynet --rm centos ping 127.0.0.1
|
注意:如果容器中不运行任何程序就会自动退出,这里使用了一个小技巧,创建容器时,让他ping自己,就不会退出了

查看两个容器的ip地址

使用ping命令让两个容器相互ping

不同网络模式容器之间互联
首先,创建两个容器centos_net1(default),centos_net2(mynet)。
1 2
| sudo docker run --rm --name centos_net1 -d -P centos ping 127.0.0.1 sudo docker run --rm --name centos_net2 --net mynet -d -P centos ping 127.0.0.1
|
使用inspect命令查看两个容器的ip address分别为
172.17.0.2
和192.168.111.1
他们在不同的网段,尝试ping,发现无法ping通,即使直接ping ip address 也不行

下面使用sudo docker network connect mynet centos_net1
命令连接mynet 和 centos_net1。
连接之后,发现centos_net1和centos_net2可以相互ping 通

通过inspect 命令检查centos_net1发现
