Docker cannot connect applications together in the same network
P粉627136450
P粉627136450 2024-02-26 20:53:13
0
1
353

我有一个 docker compose 文件,如下所示:

version: "3.9"
services:
  mysqldb:
    image: mysql:5.7
    container_name: mysqlcontainer
    command: --default-authentication-plugin=mysql_native_password
    volumes:
      - ./db/init.sql:/docker-entrypoint-initdb.d/0_init.sql
    ports:
      - 3306:3306
    expose:
      - 3306
    environment:
      MYSQL_DATABASE: "todos"
      MYSQL_USER: "admin"
      MYSQL_PASSWORD: "password"
      MYSQL_ROOT_PASSWORD: "password"
      SERVICE_TAGS: dev
      SERVICE_NAME: mysqldb
    restart: on-failure
    networks:
      - internalnet
  expressapp:
    container_name: api
    build: .
    image: expressapp:1.0
    ports:
      - "3001:3001"
    expose:
      - "3001"
    environment:
      DB_HOST: mysqldb
      DB_PORT: 3306
      DB_USER: "admin"
      DB_PASSWORD: "password"
      DB_NAME: todos
      DB_CONNECTION_LIMIT: 20
      SERVICE_TAGS: dev
      SERVICE_NAME: expressapp
      PORT: 3001
    depends_on:
      - mysqldb
    networks:
      - internalnet
networks:
  internalnet:
    driver: bridge
volumes:
  database:

如果我使用 docker compose up -d 命令启动容器并使用 ps 命令检查正在运行的容器,我将得到以下输出:

CONTAINER ID   IMAGE            COMMAND                  CREATED         STATUS         PORTS                               NAMES
9f338b733a1c   expressapp:1.0   "docker-entrypoint.s…"   2 minutes ago   Up 2 minutes   0.0.0.0:3001->3001/tcp              api
edef8027dc0a   mysql:5.7        "docker-entrypoint.s…"   2 minutes ago   Up 2 minutes   0.0.0.0:3306->3306/tcp, 33060/tcp   mysqlcontainer

但是当我尝试向服务器发出 API 请求时,我收到以下错误消息:

"There was an error processing your request: connect ECONNREFUSED 172.24.0.2:3306"

为什么是因为我将 DB_HOST 变量设置为 mysql 服务名称?

P粉627136450
P粉627136450

reply all(1)
P粉293550575

This problem may occur because expressapp is started before mysql is available for queries.

To control the service startup order, you can add healthcheck to the mysqldb service:

healthcheck:
      test: mysql ${MYSQL_DATABASE} --user=${MYSQL_USER} --password='${MYSQL_PASSWORD}' --silent --execute "SELECT 1;"
      interval: 30s
      timeout: 10s
      retries: 5

and depends_on block to expressapp

depends_on:
      mysqldb:
        condition: service_healthy

View full examplehere

For more information on this, see this answer.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template