docker 容器共享网络分为两种情况
一种是多个通过命令创建的容器共享
一种是通过多个docker-compose创建的容器容器共享,一个docker-compose内部的容器本身网络就是共享的,这里就不用讨论了
以多个 nginx 共享网络为例,所用镜像为nginx:alpine,所有示例均没有映射端口和文件,仅此仅供学习共享网络.
一、创建共享网络
无论哪种方式,第一步都是创建一个共享网络,这里创建一个名为 local_public 的网络,可以自定义,执行后会输出一个网络的ID,代表创建成功,也可通过 docker network ls 来查看网络列表.
# 创建公共网络 docker network create local_public
二、命令行启动容器共享网络
启动两个容器
docker run --network=local_public -d --name nginx_1 nginx:alpine docker run --network=local_public -d --name nginx_2 nginx:alpine
进入 nginx_1 容器,并尝试 ping 两个容器
docker exec -it nginx_1 sh / # ping nginx_1 -c 4 PING nginx_1 (172.20.0.2): 56 data bytes 64 bytes from 172.20.0.2: seq=0 ttl=64 time=0.171 ms 64 bytes from 172.20.0.2: seq=1 ttl=64 time=0.212 ms 64 bytes from 172.20.0.2: seq=2 ttl=64 time=0.207 ms 64 bytes from 172.20.0.2: seq=3 ttl=64 time=0.336 ms --- nginx_1 ping statistics --- 4 packets transmitted, 4 packets received, 0% packet loss round-trip min/avg/max = 0.171/0.231/0.336 ms / # ping nginx_2 -c 4 PING nginx_2 (172.20.0.3): 56 data bytes 64 bytes from 172.20.0.3: seq=0 ttl=64 time=0.273 ms 64 bytes from 172.20.0.3: seq=1 ttl=64 time=0.276 ms 64 bytes from 172.20.0.3: seq=2 ttl=64 time=0.353 ms 64 bytes from 172.20.0.3: seq=3 ttl=64 time=0.349 ms --- nginx_2 ping statistics --- 4 packets transmitted, 4 packets received, 0% packet loss round-trip min/avg/max = 0.273/0.312/0.353 ms
可以看到可以 ping 通 nginx_1 和 nginx_2 两个容器的IP不同,进入 nginx_2 也可以得到同样的结果
三、docker-compose 启动容器共享网络
目录结构如下
$ tree docker-test docker-test ├── nginx1 │ └── 1.yml └── nginx2 └── 2.yml
1.yml 文件如下
version: "3" services: nginx: image: nginx:alpine container_name: nginx1 networks: - local_public #着重看这里 networks: local_public: external: true #着重看这里
2.yml 文件如下
version: "3" services: nginx: image: nginx:alpine container_name: nginx2 networks: - local_public networks: local_public: external: true
分别启动两个容器
docker-compose -f nginx1/1.yml up -d docker-compose -f nginx2/2.yml up -d
进入nginx1容器,尝试 ping 两个容器
docker exec -it nginx1 sh / # ping nginx1 -c 4 PING nginx1 (172.20.0.2): 56 data bytes 64 bytes from 172.20.0.2: seq=0 ttl=64 time=0.238 ms 64 bytes from 172.20.0.2: seq=1 ttl=64 time=0.196 ms 64 bytes from 172.20.0.2: seq=2 ttl=64 time=0.208 ms 64 bytes from 172.20.0.2: seq=3 ttl=64 time=0.268 ms --- nginx1 ping statistics --- 4 packets transmitted, 4 packets received, 0% packet loss round-trip min/avg/max = 0.196/0.227/0.268 ms / # ping nginx2 -c 4 PING nginx2 (172.20.0.3): 56 data bytes 64 bytes from 172.20.0.3: seq=0 ttl=64 time=0.394 ms 64 bytes from 172.20.0.3: seq=1 ttl=64 time=0.358 ms 64 bytes from 172.20.0.3: seq=2 ttl=64 time=0.365 ms 64 bytes from 172.20.0.3: seq=3 ttl=64 time=0.348 ms --- nginx2 ping statistics --- 4 packets transmitted, 4 packets received, 0% packet loss round-trip min/avg/max = 0.348/0.366/0.394 ms
可以 ping 通 nginx1 和 nginx2 两个容器的IP不同,进入nginx2也可以得到同样的结果
未经允许请勿转载:程序喵 » 多个docker容器如何共享网络