Console9

Docker Compose: depends_on does not wait for service to be ready

Fix services starting before their dependencies are ready by adding health checks to Docker Compose depends_on.

Docker Compose starts a service as soon as its dependency container is running, not when the dependency's application is ready to accept connections. A web application container starts before MySQL finishes initialization.

What Causes This

Compose's depends_on checks that the container process has started. It does not verify the application inside is accepting connections. MySQL's container starts immediately, but the mysqld process takes 10–30 seconds to initialize on first run.

How to Fix

Add a healthcheck and condition to the dependency:

services:
  db:
    image: mysql:8
    environment:
      MYSQL_ROOT_PASSWORD: secret
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      interval: 5s
      timeout: 3s
      retries: 10

  app:
    image: myapp:latest
    depends_on:
      db:
        condition: service_healthy

Compose waits until the db health check passes before starting app.