archive2024

Docker Compose: wait for a healthy database, not a started one

depends_on alone only waits for a container to start. Use a healthcheck and condition: service_healthy so your app starts after the database is ready.

2 min read#ops#docker#docker-compose

After a fresh docker compose up, my app container started, tried to connect to PostgreSQL, got “connection refused” and exited. On the second up it worked. The database container was started in time, but PostgreSQL inside it was not ready yet.

The compose file had this:

services:
  app:
    depends_on:
      - db

This short form only waits until the db container is started. It does not wait until the service inside accepts connections.

Healthcheck plus condition

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: example
      POSTGRES_DB: app
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d app"]
      interval: 5s
      timeout: 3s
      retries: 10
      start_period: 10s

  app:
    build: .
    depends_on:
      db:
        condition: service_healthy
    environment:
      DATABASE_URL: postgres://postgres:example@db:5432/app

Now Compose starts db, runs pg_isready every 5 seconds, and starts app only when the check passes.

Check the state with:

docker compose ps

The STATUS column shows (healthy), (health: starting) or (unhealthy).

Other services

Test commands I have used:

Service Test command
PostgreSQL pg_isready -U postgres
MySQL / MariaDB mysqladmin ping -h localhost
Redis redis-cli ping
InfluxDB 2 influx ping
HTTP app curl -fsS http://localhost:8080/health (only if curl is in the image)

The command runs inside the container. Many slim images do not include curl or wget. Check before you use them, or use a tool the image already has.

Waiting for a migration job

Besides service_healthy there is service_started (the default, same as the short form) and service_completed_successfully. The last one waits until a one-shot container exits with code 0, which is nice for migrations:

  migrate:
    build: .
    command: ["python", "manage.py", "migrate"]
    depends_on:
      db:
        condition: service_healthy
  app:
    depends_on:
      migrate:
        condition: service_completed_successfully

What this does not fix

It only works at startup. If the database restarts later, app is not restarted or paused, so the app still needs retry logic for lost connections. I first hoped the healthcheck would cover that too. It does not.

start_period gives a slow service time to boot; failures in that period do not count against retries. And in Docker Swarm, depends_on is ignored.