多个docker compose启动的容器之间通信实现过程
作者:Allocator
背景
本地或者某些开发环境我们会使用docker-compose.yml
来编排一组容器,同时会给这一组容器分配默认的网络外部名称
,
以busybox镜像举个例子:
services: g1: image: busybox:latest container_name: g1 restart: unless-stopped command: ['sh', '-c', 'echo "Hello from BusyBox!" && sleep 3600'] networks: default: name: group1_net
使用docker compose docker-compose.yml up -d
启动后使用docker network ls
就可以看到名字为group1_net的默认网络
docker network ls ... eda03dfdc6ed group1_net bridge local
一般我们会将这一组相关的容器编排的docker-compose.yml文件放置于一个文件夹中进行维护,当本地存在多组编排的容器的docker-compose.yml文件的时候,也就相当于会有多个文件夹用于存放和管理这些文件,比如本地有两组编排的容器,
那么本地文件结构如下:
tree . ├── group1 │ └── docker-compose.yml └── group2 └── docker-compose.yml 2 directories, 2 files
启动这两组容器,可以看到相应的网络同时创建
8d6bce7a03cc group1_net bridge local 080cfe997ef2 group2_net bridge local
这个时候会引入一个问题,这种方式会让启动的每一组容器网络是隔离的
,一般情况下编排容器组的时候确实是每一组容器应该做网络隔离,但是某些场景还是会遇到需要夸容器组的网络访问,
最佳实现
实现跨容器组(docker-compose)的容器访问最佳实现还是将需要跨组访问的容器组分配到同一个网络
.
这个实现非常简单,首先使用如下指令创建一个network公共网络.
docker network create group_share_net
然后修改每一个容器组的docker-compose.yml
的默认网络配置项
.将其网络名字改为前一步创建的公共网络名,即group_share_net
同时配置external: true,表示此docker-compose.yml使用已经定义好的外部网络
.
修改后的结果如下:
services: g1: image: busybox:latest container_name: g1 restart: unless-stopped command: ['sh', '-c', 'echo "Hello from BusyBox!" && sleep 3600'] networks: default: external: true name: group_share_net
以及
services: g2: image: busybox:latest container_name: g2 restart: unless-stopped command: ['sh', '-c', 'echo "Hello from BusyBox!" && sleep 3600'] networks: default: external: true name: group_share_net
再重启两个容器组,这个时候进入到容器g1去尝试ping通容器g2.
docker exec -it g1 /bin/sh / # ping -c 5 g2 PING g2 (172.20.0.2): 56 data bytes 64 bytes from 172.20.0.2: seq=0 ttl=64 time=0.061 ms 64 bytes from 172.20.0.2: seq=1 ttl=64 time=0.024 ms 64 bytes from 172.20.0.2: seq=2 ttl=64 time=0.026 ms 64 bytes from 172.20.0.2: seq=3 ttl=64 time=0.017 ms 64 bytes from 172.20.0.2: seq=4 ttl=64 time=0.019 ms --- g2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max = 0.017/0.029/0.061 ms
这里就可以看出group1中的g1容器可以正常访问到group2中的g2容器,表明两个docker-compose.yml编排的容器就能够实现相互访问.
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。