docker容器之间互相通信访问可以用bridge的方式

    1. $ docker network create bridge-network
    2. affee02f8b0570be78e45247e67d4a255cd04718a566a7fe79578541e0ccbbbd
    3. # 查看当前网络
    4. $ docker network ls
    5. NETWORK ID NAME DRIVER SCOPE
    6. a91a41347559 bridge bridge local
    7. affee02f8b05 bridge-network bridge local
    8. 74fb8d7c6f3b host host local
    9. 9f512edb4272 none null local

    可以看到我们成功的创建了一个名字叫做bridge-network的网络。
    这个时候我们创建多个容器,并启动容器将容器连接到该网络中:

    1. docker run -it --name <容器名> ---network <bridge> --network-alias <网络别名> <镜像名>
    1. $ docker run -it --name network-nginx-1 --network bridge-network --network-alias test1 nginx:latest
    2. $ docker run -it --name network-nginx-2 --network bridge-network --network-alias test2 nginx:latest

    这个时候查看

    1. $ docker ps
    2. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
    3. 73112579472f nginx:latest "nginx -g 'daemon of…" 3 minutes ago Up 4 seconds 80/tcp network-nginx-2
    4. 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

    1. $ docker exec -it 73112579472f /bin/bash
    2. root@73112579472f:/# ping test2
    3. PING test2 (172.18.0.3) 56(84) bytes of data.
    4. 64 bytes from 73112579472f (172.18.0.3): icmp_seq=1 ttl=64 time=0.059 ms
    5. 64 bytes from 73112579472f (172.18.0.3): icmp_seq=2 ttl=64 time=0.108 ms
    6. 64 bytes from 73112579472f (172.18.0.3): icmp_seq=3 ttl=64 time=0.105 ms
    7. 64 bytes from 73112579472f (172.18.0.3): icmp_seq=4 ttl=64 time=0.314 ms
    8. 64 bytes from 73112579472f (172.18.0.3): icmp_seq=5 ttl=64 time=0.106 ms
    9. ^C
    10. --- test2 ping statistics ---
    11. 5 packets transmitted, 5 received, 0% packet loss, time 84ms
    12. rtt min/avg/max/mdev = 0.059/0.138/0.314/0.090 ms

    这样就能访问到test2网络的容器了。