Docker Compose Container 之间相互通信

Docker Compose Container 之前相互通信

因 links 属性已被废弃,官方建议使用 networks 来将几个container划分至一个网络,从而实现container之间互通。

创建一个桥接网络

docker network create YOUR_NET_NAME
默认网络方式即为桥接
YOUR_NET_NAME为你自定义的网络名称

修改docker-compose.yml文件

  1. YOUR_NET_NAME网络添加到 container 配置中
  2. 在与services同级的 networks 配置中,添加 YOUR_NET_NAMEexternal: 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数据库

添加新评论