docker容器之间互相通信访问可以用bridge的方式
$ docker network create bridge-network
affee02f8b0570be78e45247e67d4a255cd04718a566a7fe79578541e0ccbbbd
# 查看当前网络
$ docker network ls
NETWORK ID NAME DRIVER SCOPE
a91a41347559 bridge bridge local
affee02f8b05 bridge-network bridge local
74fb8d7c6f3b host host local
9f512edb4272 none null local
可以看到我们成功的创建了一个名字叫做bridge-network的网络。
这个时候我们创建多个容器,并启动容器将容器连接到该网络中:
docker run -it --name <容器名> ---network <bridge> --network-alias <网络别名> <镜像名>
$ docker run -it --name network-nginx-1 --network bridge-network --network-alias test1 nginx:latest
$ docker run -it --name network-nginx-2 --network bridge-network --network-alias test2 nginx:latest
这个时候查看
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
73112579472f nginx:latest "nginx -g 'daemon of…" 3 minutes ago Up 4 seconds 80/tcp network-nginx-2
bcdaec32e54d nginx:latest "nginx -g 'daemon of…" 7 minutes ago Up 7 minutes 80/tcp network-nginx-1
我们进入network-nginx-1尝试ping一下network-nginx-2
$ docker exec -it 73112579472f /bin/bash
root@73112579472f:/# ping test2
PING test2 (172.18.0.3) 56(84) bytes of data.
64 bytes from 73112579472f (172.18.0.3): icmp_seq=1 ttl=64 time=0.059 ms
64 bytes from 73112579472f (172.18.0.3): icmp_seq=2 ttl=64 time=0.108 ms
64 bytes from 73112579472f (172.18.0.3): icmp_seq=3 ttl=64 time=0.105 ms
64 bytes from 73112579472f (172.18.0.3): icmp_seq=4 ttl=64 time=0.314 ms
64 bytes from 73112579472f (172.18.0.3): icmp_seq=5 ttl=64 time=0.106 ms
^C
--- test2 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 84ms
rtt min/avg/max/mdev = 0.059/0.138/0.314/0.090 ms
这样就能访问到test2网络的容器了。