多个docker容器如何共享网络
多个docker容器如何共享网络
一、创建共享网络
无论哪种方式,第一步都是创建一个共享网络,这里创建一个名为 local_public 的网络,可以自定义,执行后会输出一个网络的ID,代表创建成功,也可通过 docker network ls 来查看网络列表.
# 创建公共网络
docker network create local_public
二、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 #着重看这里 不加网桥名不前缀,必需提前手动创建这个网络 默认是false,会加前缀,自动创建
手动创建这个网络
docker network create local_pullic
docker network ls
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也可以得到同样的结果
参考文档:
[Haima的博客]
http://www.cnblogs.com/haima/