作为新手,docker的容器网络很需要了解透彻。最近公司一直在推docker的项目,这里不讲解link,因为该方法已经落伍,官方已丢弃。
下面写下docker容器网络互联的几个个人见解。
[root@mrfire ~]# cat /etc/redhat-release
CentOS Linux release 7.5.1804 (Core)
[root@mrfire ~]# docker --version
Docker version 19.03.4, build 9013bf583a
一、加到同一个网络
[root@mrfire ~]# docker run -itd --rm --name=busybox1 busybox
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
7c9d20b9b6cd: Pull complete
Digest: sha256:fe301db49df08c384001ed752dff6d52b4305a73a7f608f21528048e8a08b51e
Status: Downloaded newer image for busybox:latest
8384f87b8c30093a289d4070a373d602868180aee56f39ab7ba053f5eb3b1a90
[root@mrfire ~]# docker run -itd --rm --name=busybox2 busybox
456a1c7a1749cf75d64d7c6e358a45287de673329ee27d03e7f12cd4c88eec26
[root@mrfire ~]# docker exec -it busybox1 ping busybox2
ping: bad address 'busybox2'
这个其实用的就是默认的网桥模式,跟指定--network=bridge一样。
二、先创建网卡再ping
[root@mrfire ~]# docker network c
connect create
[root@mrfire ~]# docker network create test
ea0ece10c4caf92701cc278fbbc469f5b144bbdbe81343d1f0e04a630e5f7e3d
[root@mrfire ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
07f7a2cdeb52 bridge bridge local
e6a64cd75710 host host local
968d0bad2bda none null local
ea0ece10c4ca test bridge local
[root@mrfire ~]# docker run -itd --rm --name=busybox1 --net=test busybox
2acdb2c1550906d18af2f3274b92c52ff7cdc4429c6999df41351e9cf8d15f80
[root@mrfire ~]# docker run -itd --rm --name=busybox2 --net=test busybox
319e84744830208f29e508c3f7251ed37f9277bcbc7f2e48e3d4e486b04735d2
[root@mrfire ~]# docker exec -it busybox1 ping busybox2
PING busybox2 (172.18.0.3): 56 data bytes
64 bytes from 172.18.0.3: seq=0 ttl=64 time=0.100 ms
--- busybox2 ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 0.100/0.100/0.100 ms
三、container模式
root@mrfire ~]# docker run -itd --rm --name=busybox1 --net=test busybox
3d87a3f91e39eb3db464d4af926c36c9d6a2c5a3ddd4bfed791109a9844e99c0
[root@mrfire ~]# docker run -itd --rm --name=busybox2 --network=container:busybox1 busybox
7c7bdfc5bdbb56ff1236d3b5d6255236f9947eae484153c22c5ba4cffb6c6fd5
[root@mrfire ~]# docker exec -it busybox2 ping busybox1
PING busybox1 (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.047 ms
--- busybox1 ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 0.047/0.047/0.047 ms
[root@mrfire ~]# docker inspect busybox1 --format '{{.NetworkSettings.Networks.test.IPAddress}}'
172.18.0.2
[root@mrfire ~]# docker inspect busybox2 --format '{{.NetworkSettings.Networks.test.IPAddress}}'
<no value>
可以看出container模式下,busybox2是和busybox1共享一G个NETWORK NAMESPACE,而不是和宿主机共享(--net=host).
建议:创建一块网卡,也就是第一种 docker network create
网友评论