docker-compose 之间的通信

docker-comopse网络

使用docker-compose up启动容器后,这些容器都会被加入app_default网络中。使用docker network ls可以查看网络列表,docker network inspect 可以查看对应网络的配置。
似乎多个docker-compose之前的网络是不互通的,导致不能直接用容器名连接- -下面就介绍一个可以多个compose通信的方法。

创建一个自定义网络

1
docker network create cooky-net

创建两个docker-compose

这边用mysql跟nacos做演示,就直接拿我的部署文件,省事!

mysql、redis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
version: '3'

services:
mysql:
image: mysql:5.7.24
container_name: mysql
networks:
- default
- cooky-net
environment:
MYSQL_ROOT_PASSWORD: 123456
ports:
- 3306:3306
volumes:
- /home/mysql/data:/var/lib/mysql
redis:
image: redis:4.0.14
container_name: redis
networks:
- default
- cooky-net
command: --appendonly yes
volumes:
- /home/redis:/data
ports:
- 6379:6379
networks:
cooky-net:
external: true

nacos

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
version: '3'

services:
nacos:
image: nacos/nacos-server:latest
container_name: nacos
networks:
- default
- cooky-net
environment:
- "PREFER_HOST_MODE=hostname"
- "MODE=standalone"
- "SPRING_DATASOURCE_PLATFORM=mysql"
- "MYSQL_MASTER_SERVICE_HOST=mysql"
- "MYSQL_MASTER_SERVICE_DB_NAME=nacos"
- "MYSQL_MASTER_SERVICE_PORT=3306"
- "MYSQL_MASTER_SERVICE_USER=root"
- "MYSQL_MASTER_SERVICE_PASSWORD=123456"
- "MYSQL_SLAVE_SERVICE_HOST=mysql"
- "MYSQL_SLAVE_SERVICE_PORT=3306"
volumes:
- /home/nacos/logs/:/home/nacos/logs
ports:
- 8848:8848
restart: on-failure
networks:
cooky-net:
external: true

先启动mysql、redis那个再启动nacos,发现nacos启动正常,使用容器名也能正确的连接上数据库,实验成功!💣💣💣

end