docker 网络互通

自定义网络
查看所有的docker网络
网络模式

[root@docker ~]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
a4d70d5796e4   bridge    bridge    local
fc2805a7d397   host      host      local
c680f1ffd777   none      null      local

bridge 桥接 docker上面搭桥(默认)
none 不配置网络
host 和宿主机共享网络
container 容器内网络连通 (用的少)

测试

docker run -P -d --name tomcat01 --net bridge tomcat

默认 --net bridge

自定义网络

[root@docker ~]# docker network create --driver bridge --subnet 192.168.0.0/16  --gateway 192.168.0.1 mynet
58aaebabf20846d0f03670a5017e3eb6609138d26e1d7a35ef61646addc1e49e
[root@docker ~]# 
[root@docker ~]# docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
a4d70d5796e4   bridge    bridge    local
fc2805a7d397   host      host      local
58aaebabf208   mynet     bridge    local
c680f1ffd777   none      null      local
[root@docker ~]# 

创建自定义网络 --driver 桥接 默认也是桥接

创建好网络后将容器添加到网络

[root@docker ~]# docker run -d -P --name  tomcat01 --net mynet tomcat:7.0
25515d748acd7864f575eb6929722e8ad6803c8f3af2295da3fe34a5d1b2e8ca
[root@docker ~]# docker run -d -P --name  tomcat02 --net mynet tomcat:7.0
85466bf00278affdd38ea626e8ebdf634d243b766263bb1c06f7afb209fd5b65
[root@docker ~]# docker network inspect mynet

自定义的网络可以使用--link也可以ping名字

[root@docker ~]# docker exec -it tomcat01  ping 192.168.0.3
PING 192.168.0.3 (192.168.0.3) 56(84) bytes of data.
64 bytes from 192.168.0.3: icmp_seq=1 ttl=64 time=0.147 ms
64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=0.057 ms
^C
--- 192.168.0.3 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 2ms
rtt min/avg/max/mdev = 0.057/0.102/0.147/0.045 ms
[root@docker ~]# docker exec -it tomcat01  ping tomcat02
PING tomcat02 (192.168.0.3) 56(84) bytes of data.
64 bytes from tomcat02.mynet (192.168.0.3): icmp_seq=1 ttl=64 time=0.054 ms
64 bytes from tomcat02.mynet (192.168.0.3): icmp_seq=2 ttl=64 time=0.055 ms
64 bytes from tomcat02.mynet (192.168.0.3): icmp_seq=3 ttl=64 time=0.058 ms
^C
--- tomcat02 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.054/0.055/0.058/0.008 ms

好处
redis
mysql
不同集群使用不同网络

不同网段相互ping
容器与网段打通
连接一个容器到一个网络
connect
打通tomcat01 到 mynet

docker network connect mynet tom01
docker network inspect mynet            
"65fa00ce93b6efa63aee2013154999b8529517eaaace77d7438abccab2666710": {
                "Name": "tom01",
                "EndpointID": "35bdb8780df35a272dc9bea5db0fb49c4b6a601d960b719d82e809c3586cc5ab",
                "MacAddress": "02:42:c0:a8:00:04",
                "IPv4Address": "192.168.0.4/16",
                "IPv6Address": ""

可以看到tom01已经在mynet下
一个容器两个ip

posted @ 2022-04-20 15:18  supermao12  阅读(302)  评论(0编辑  收藏  举报