参考
命令
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network
create Create a network
disconnect Disconnect a container from a network
inspect Display detailed information on one or more networks
ls List networks
prune Remove all unused networks #清理使用,谨慎使用
rm Remove one or more networks
测试
bridge
# 创建参数参考https://docs.docker.com/reference/cli/docker/network/create/#options
# -d 指定network类型,不填默认bridge
# --subnet 指定网段可不加
# --gateway 指定网关可不加
docker network create --subnet 172.60.0.0/16 --gateway 172.60.0.1 -d bridge test-bridge
容器
# 这里busybox1不指定network,默认使用bridge,busybox2则指定test-bridge
docker run -itd --name busybox1 busybox
docker run -itd --network test-bridge --name busybox2 busybox
network
docker network inspect bridge # busybox1分配bridge ip 172.17.0.4
docker network inspect test-bridge # busybox2分配test-bridge ip 172.60.0.2
# 这时两个容器不互通,相互ping ip会失败
docker network connect bridge busybox2 # 将busybox2连接bridge,分配ip 172.17.0.5
# 这时两个容器能够通过bridge分配的ip相互ping
docker network disconnect bridge busybox2 # busybox2断连bridge,并将busybox1连接test-bridge
docker network connect test-bridge busybox1 # busybox1分配test-bridge ip 172.60.0.3
# 这时同样能通过test-bridge分配的ip相互ping,还能通过相应的name相互ping
/ # ping busybox1
PING busybox1 (172.60.0.3): 56 data bytes
64 bytes from 172.60.0.3: seq=0 ttl=64 time=2.128 ms
64 bytes from 172.60.0.3: seq=1 ttl=64 time=0.065 ms
64 bytes from 172.60.0.3: seq=2 ttl=64 time=0.052 ms
^C
--- busybox1 ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max = 0.052/0.748/2.128 ms
docker network disconnect test-bridge busybox1 # 先断连
docker network connect --ip 172.60.0.20 --alias busybox001 test-bridge busybox1
# 指定网段下的ip,并起一个别名
# 这样不仅可以ping 容器名,也可以ping 别名,对应指定ip
/ # ping busybox1
PING busybox1 (172.60.0.20): 56 data bytes
64 bytes from 172.60.0.20: seq=0 ttl=64 time=0.138 ms
64 bytes from 172.60.0.20: seq=1 ttl=64 time=0.053 ms
^C
--- busybox1 ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 0.053/0.095/0.138 ms
/ # ping busybox001
PING busybox001 (172.60.0.20): 56 data bytes
64 bytes from 172.60.0.20: seq=0 ttl=64 time=0.038 ms
64 bytes from 172.60.0.20: seq=1 ttl=64 time=0.069 ms
64 bytes from 172.60.0.20: seq=2 ttl=64 time=0.082 ms
64 bytes from 172.60.0.20: seq=3 ttl=64 time=0.046 ms
^C
--- busybox001 ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max = 0.038/0.058/0.082 ms
总结
- 同一bridge下的容器可通过ip进行相互访问
- 默认bridge下的容器不支持DNS,仅能通过ip访问
- 自建bridge可以使用容器名称进行访问,若指定别名,也可以使用别名