Docker Compose Container 之前相互通信
因 links 属性已被废弃,官方建议使用 networks 来将几个container划分至一个网络,从而实现container之间互通。
docker network create YOUR_NET_NAME
默认网络方式即为桥接
YOUR_NET_NAME
为你自定义的网络名称
docker-compose.yml
文件YOUR_NET_NAME
网络添加到 container
配置中services
同级的 networks
配置中,添加 YOUR_NET_NAME
为 external: true
,如:openresty/docker-compose.yml
version: "3"
services:
openresty:
container_name: openresty
image: openresty/openresty
restart: always
networks:
- YOUR_NET_NAME
volumes:
- ./conf:/usr/local/openresty/nginx/conf
- ./web:/web
ports:
- "80:80"
- "443:443"
networks
YOUR_NET_NAME:
external: true
重新加载配置 docker-compose up -d
mariadb/docker-compose.yml
version: "3"
services:
mariadb:
container_name: mariadb
image: mariadb
restart: always
networks:
- YOUR_NET_NAME
environment:
MYSQL_ROOT_PASSWORD: root
volumes:
- ./data:/var/lib/mysql
- ./conf/my.cnf:/etc/mysql/my.cnf
ports:
- "13306:3306"
networks
YOUR_NET_NAME:
external: true
重新加载配置 docker-compose up -d
注意:networks 中必须设置 external 为true,否则无法正常通信
openresty 和 mariadb 现在可以互通了!
在 openresty
中,可以直接通过 mariadb:3306
来访问mariadb数据库