Administrator
发布于 2022-11-04 / 1029 阅读 / 0 评论 / 0 点赞

docker compose 连接使用外部其他容器

本地项目构建了一个compose的编排,但是需要使用其他容器的redis和mysql。直接构建的时候两个容器连接超时。

docker inspect mysql-local
docker inspect job

发现两个容器不在一个网段下面。所以导致连接不上。
解决方案

将外部的容器加入到指定自定义的网络中。让compose编排和mysql容器在一个网络下即可连接。

docker network create local_compose_env --driver bridge
docker network disconnect bridge mysql-local
docker network connect local_compose_env mysql-local

compose使用自定义网络

version: "3.0"
services:
  admin:
    container_name: admin
    build:
      context: ./admin
      dockerfile: ./Dockerfile
    # mac m1 指定运行平台
    platform: "linux/amd64"
    restart: always
    ports:
      - 8001:8001
    networks:
      - default
  rest:
    container_name: rest
    build:
      context: ./rest
      dockerfile: ./Dockerfile
    platform: "linux/amd64"
    restart: always
    ports:
      - 8000:8000
    networks:
      - default
  binlog:
    container_name: binlog
    build:
      context: ./binlog
      dockerfile: ./Dockerfile
    platform: "linux/amd64"
    restart: always
    networks:
      - default
  job:
    container_name: job
    build:
      context: ./job
      dockerfile: ./Dockerfile
    platform: "linux/amd64"
    restart: always
    networks:
      - default
  worker:
    container_name: worker
    build:
      context: ./worker
      dockerfile: ./Dockerfile
    platform: "linux/amd64"
    restart: always
    networks:
      - default
networks:
  default:
    external:
      name: local_compose_env

最后

 docker compose up -d

image-1667525500873

检查连接,请求成功