DEV3 Technologies home

DEV3 Developer Forum

How do I write a docker-compose.yml for a web app with a database that actually waits for the DB?

DevOps helpSolved0 views
dev3 ·

My app container starts before MySQL is ready and crashes with "Connection refused". I used depends_on, but it did not help. How do I fix it properly?

#docker#docker-compose#mysql

0

1 reply

dev3 · Accepted answer

depends_on alone only controls start order, not readiness. Add a healthcheck and use the service_healthy condition (Compose v2 / Compose Specification).

services:
  app:
    build: .
    ports:
      - "8080:8080"
    environment:
      DB_HOST: db
      DB_DATABASE: app
      DB_USERNAME: app
      DB_PASSWORD: ${DB_PASSWORD}
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: mysql:8.4
    environment:
      MYSQL_DATABASE: app
      MYSQL_USER: app
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
    volumes:
      - dbdata:/var/lib/mysql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-p${DB_ROOT_PASSWORD}"]
      interval: 5s
      timeout: 3s
      retries: 20

volumes:
  dbdata:

Key points

  • Containers reach each other by service name (db), not localhost.
  • localhost inside the app container is the app itself. This is the usual cause of "Connection refused".
  • Secrets come from a .env file next to the compose file (never commit it).
  • Named volume dbdata keeps data across docker compose down; down -v deletes it.
  • The first start initialises the database from the env variables only when the data volume is empty. Changing the password later has no effect on an existing volume.
  • Do not publish the DB port (3306:3306) on a public server unless required; the app reaches it on the internal network.

Also make the app retry connections; healthchecks do not cover a DB restart while running. Commands: docker compose up -d, docker compose logs -f app, docker compose ps.

You can scaffold files with the Dockerfile and Compose generator.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.