1

I have a docker compose file which looks as follows:

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:

If i start the containers using the docker compose up -d command and check the containers that are running using the ps command i'm getting the following output:

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

But when i try when i want to make API request to the server I'm getting the following error message:

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

Why is is that beacause i'm setting the DB_HOST variable to the mysql service name?

crispengari
  • 7,901
  • 7
  • 45
  • 53

1 Answers1

1

This issue probably happens because expressapp starts before mysql is available for queries.

To control services start order you can add healthcheck to 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  

See full example here

More about it in this answer.

rok
  • 9,403
  • 17
  • 70
  • 126