Medium DevOps

Docker Compose Healthchecks and depends_on: Start Laravel, MySQL and Redis in the Right Order

Short-form depends_on never waited for MySQL. Use healthchecks with service_healthy and service_completed_successfully to boot Laravel, MySQL and Redis reliably.

22 Nov, 2026 8 min Updated 23 Oct, 2026 5 Code blocks
Diagram
graph LR A[mysql healthy] --> C[migrate runs] C -->|exit code 0| D[app starts] B[redis healthy] --> D B --> E[queue starts] C -->|exit code 0| E D --> F[app healthy] F --> G[compose up wait returns]

A new developer clones the repo, runs docker compose up, and the app container exits with SQLSTATE[HY000] [2002] Connection refused. They run it again and it works. CI fails the same way about one run in ten. Someone adds sleep 15 to the entrypoint, the flakiness drops, and every local startup is now 15 seconds slower, including on machines where MySQL is ready in four.

The root cause is a misunderstanding of depends_on. In its short form it only orders container creation: Compose starts MySQL, then starts the app, without waiting for MySQL to accept connections. On a first boot, the MySQL image initialises its data directory and runs init scripts, which can take 20 to 60 seconds. The app is long past its first query by then.

Why wait-for Scripts Were Never Enough

Before Compose supported health conditions, the standard fix was a loop in the entrypoint:

#!/bin/sh
# entrypoint.sh: the "wait-for" approach
until nc -z mysql 3306; do
  echo "waiting for mysql..."
  sleep 1
done
php artisan migrate --force
exec php-fpm

It works more often than sleep, but it checks the wrong thing. An open TCP port means a process is listening, not that the database is ready: the schema may not exist yet, the user from MYSQL_USER may not be created, Redis may still be loading its dataset. The loop has no timeout, so a misconfigured host name hangs the container forever with a friendly "waiting" message. And the logic is copied into every image that needs it, often with nc installed only for this purpose.

Healthchecks move that knowledge to where it belongs: the dependency describes how to tell it is ready, and Compose waits for that state before starting what depends on it.

Healthchecks plus depends_on Conditions

Here is a Laravel stack with MySQL, Redis, a one-shot migration service, the web app and a queue worker:

services:
  mysql:
    image: mysql:8.4
    environment:
      MYSQL_DATABASE: shop
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
    healthcheck:
      # -h 127.0.0.1 forces TCP: the temporary init server has networking disabled
      test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p$$MYSQL_ROOT_PASSWORD --silent"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 60s
      start_interval: 2s

  redis:
    image: redis:7.4-alpine
    healthcheck:
      test: ["CMD-SHELL", "redis-cli ping | grep -q PONG"]
      interval: 10s
      timeout: 3s
      retries: 5
      start_period: 5s

  migrate:
    image: shop-app:latest
    command: ["php", "artisan", "migrate", "--force"]
    restart: "no"
    depends_on:
      mysql: { condition: service_healthy }

  app:
    image: shop-app:latest
    healthcheck:
      test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8080/up"]
      interval: 15s
      timeout: 3s
      retries: 3
      start_period: 20s
    depends_on:
      mysql: { condition: service_healthy, restart: true }
      redis: { condition: service_healthy }
      migrate: { condition: service_completed_successfully }

  queue:
    image: shop-app:latest
    command: ["php", "artisan", "queue:work", "--tries=3", "--max-time=3600"]
    depends_on:
      redis: { condition: service_healthy }
      migrate: { condition: service_completed_successfully }

The long form of depends_on accepts a condition:

  • service_started: the default. Only waits for the container to start.
  • service_healthy: waits until the dependency's healthcheck reports healthy. If it becomes unhealthy or never gets there, up fails instead of starting the dependant.
  • service_completed_successfully: waits until the dependency exits with code 0. Perfect for migrations, seeders and asset builds.

The healthcheck fields control timing. interval is the time between checks, timeout how long one check may take, retries how many consecutive failures mark it unhealthy. start_period is a grace window during which failures do not count, and start_interval (Docker Engine 25 and later) lets you check more often during that window, so a fast boot is detected in two seconds instead of ten.

The Startup Graph

graph LR A[mysql healthy] --> C[migrate runs] C -->|exit code 0| D[app starts] B[redis healthy] --> D B --> E[queue starts] C -->|exit code 0| E D --> F[app healthy] F --> G[compose up wait returns]

Migrations run exactly once, after MySQL is genuinely ready, and before any process that might query a table that does not exist yet. The app and the worker start in parallel once their own conditions are met. No sleeps, no loops, and docker compose up --wait returns only when the whole graph is green.

Details That Make the MySQL Check Honest

Two traps in MySQL healthchecks catch almost everyone.

mysqladmin ping succeeds on access denied. Its exit code is 0 whenever the server is running, even if authentication fails. That is actually what you want for a liveness-style check, but do not mistake it for "my app user can log in". If you need that guarantee, run a real query with the application credentials: mysql -h 127.0.0.1 -u$$MYSQL_USER -p$$MYSQL_PASSWORD -e 'SELECT 1' $$MYSQL_DATABASE.

The init server is not the real server. On first start, the entrypoint launches a temporary server with networking disabled to run init scripts, then restarts it. A healthcheck that connects over the local socket can report healthy against that temporary server, and your app connects just as it shuts down. Forcing TCP with -h 127.0.0.1 makes the check fail until the final server is listening.

Also note the $$. Compose interpolates $VAR from your shell or .env file when it parses the file. $$ escapes it, so the variable is expanded inside the container, where MYSQL_ROOT_PASSWORD is actually set.

Operating the Stack

Most of the value shows up when you script around it:

# Start everything and block until every service is running or healthy (non-zero exit otherwise)
docker compose up -d --wait --wait-timeout 120

docker compose ps                     # STATUS column shows (healthy) / (health: starting)
docker inspect --format '{{json .State.Health.Log}}' shop-mysql-1 | jq '.[-1]'
docker compose logs migrate           # a one-shot service that failed shows why here

--wait turns "is the stack up?" into an exit code, which is what CI needs. When something hangs, the health log in docker inspect shows the exact output of the last checks, which is usually enough to see whether you are probing the wrong host, the wrong port or a command that does not exist in the image.

Testing the Stack in CI

Startup ordering is infrastructure, but it can be tested like code. Tag a few Pest tests that only make sense inside the composed environment:

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Schema;

it('reaches mysql through the compose network', function () {
    expect(DB::select('select 1 as ok')[0]->ok)->toEqual(1);
})->group('compose');

it('ran the migrations before the app started', function () {
    expect(Schema::hasTable('migrations'))->toBeTrue()
        ->and(DB::table('migrations')->count())->toBeGreaterThan(0);
})->group('compose');

it('reads back what it writes to redis', function () {
    Redis::set('compose:smoke', 'ok');

    expect(Redis::get('compose:smoke'))->toBe('ok');
})->group('compose');

Then run them against a freshly started stack in CI:

docker compose up -d --wait --wait-timeout 180 || { docker compose ps; docker compose logs --tail=50; exit 1; }
docker compose exec -T app php artisan test --group=compose
docker compose down -v

The || { ...; exit 1; } branch prints the state and recent logs of every service before failing, so a red build tells you which healthcheck never passed. Starting from down -v volumes each time also exercises the slow first-boot path that local machines rarely hit.

Common Pitfalls

Healthcheck commands that do not exist in the image. curl is missing from many slim and Alpine-based images, and a missing binary just looks like an unhealthy container. Check with docker compose exec app which curl, or use wget -qO- or a small PHP script.

Expecting depends_on to handle runtime failures. Conditions are evaluated when Compose starts services. If MySQL crashes an hour later, the app is not stopped or restarted. restart: true only restarts the dependant when Compose itself restarts the dependency, for example with docker compose restart mysql. Your app still needs retries and sensible connection timeouts.

Treating one-shot services as long-running. A migrate service with restart: unless-stopped loops forever, and service_completed_successfully never sees a final exit. One-shot services need restart: "no".

Overly aggressive intervals. A healthcheck every second on every service burns CPU on laptops and floods health logs. Use a short start_interval for fast detection at boot and a relaxed interval afterwards.

Assuming Compose healthchecks restart containers. Plain Docker Engine marks a container unhealthy but does not restart it. Restarts on health need an orchestrator or a separate watchdog.

When to Use Health Conditions, and When Not To

Use service_healthy for every stateful dependency the app needs at boot: databases, caches, search engines, message brokers. Use service_completed_successfully for setup steps that must finish first: migrations, seeders, bucket creation in MinIO, frontend builds.

Keep plain service_started (or no depends_on at all) for services that tolerate their dependencies arriving late, such as a reverse proxy that retries upstreams or a worker with its own reconnect loop. Over-constraining the graph turns a missing optional service into a stack that refuses to start.

Wait-for loops still have a place when the dependency lives outside Compose, for example a managed database in CI or an init container in Kubernetes, where Compose conditions do not exist. Even then, give the loop a timeout and check readiness with a real query, not an open port. And in every environment, keep retry logic in the application itself: healthchecks make startup deterministic, they do not make dependencies immortal.

Interactive challenge

Try the challenge

Practice what you just learned. Write your solution, reveal hints if you get stuck.

Instructions

Model Docker Compose startup rules. canStart(deps, states) in JavaScript / can_start(deps, states) in Python returns true when every dependency condition is satisfied. deps maps a service name to one of 'service_started', 'service_healthy' or 'service_completed_successfully'; any other condition throws an Error (JS) or raises ValueError (Python). states maps a service name to an object/dict with status ('created', 'running' or 'exited'), health ('healthy', 'unhealthy', 'starting' or null/None) and exitCode (JS) / exit_code (Python). A dependency missing from states is not satisfied. service_started needs status 'running'; service_healthy needs status 'running' and health 'healthy'; service_completed_successfully needs status 'exited' and exit code 0. An empty deps object is satisfied. startupOrder(services) / startup_order(services) receives a map from service name to a list of dependency names and returns the start order: a service comes after all its dependencies, and whenever several services are ready at the same time, pick the alphabetically smallest first. Throw an Error (JS) / raise ValueError (Python) when a dependency is not a known service (message must contain 'unknown service' in JS) or when there is a cycle (message must contain 'cycle' in JS).

Starter code

python
CONDITIONS = {"service_started", "service_healthy", "service_completed_successfully"}


def can_start(deps: dict[str, str], states: dict[str, dict]) -> bool:
    """deps:   {"mysql": "service_healthy", "migrate": "service_completed_successfully"}
    states: {"mysql": {"status": "running", "health": "healthy", "exit_code": None}, ...}
    """
    # TODO: unknown condition -> ValueError
    # TODO: a dependency missing from states -> not satisfied
    # TODO: service_started -> status == "running"
    # TODO: service_healthy -> status == "running" and health == "healthy"
    # TODO: service_completed_successfully -> status == "exited" and exit_code == 0
    raise NotImplementedError


def startup_order(services: dict[str, list[str]]) -> list[str]:
    # TODO: topological order; when several services are ready, take them alphabetically
    # TODO: unknown dependency or a cycle -> ValueError
    raise NotImplementedError
javascript
const CONDITIONS = ['service_started', 'service_healthy', 'service_completed_successfully'];

/**
 * deps:   { mysql: 'service_healthy', migrate: 'service_completed_successfully' }
 * states: { mysql: { status: 'running', health: 'healthy', exitCode: null }, ... }
 */
function canStart(deps, states) {
  // TODO: unknown condition -> throw Error
  // TODO: a dependency missing from states -> not satisfied
  // TODO: service_started -> status === 'running'
  // TODO: service_healthy -> status === 'running' && health === 'healthy'
  // TODO: service_completed_successfully -> status === 'exited' && exitCode === 0
  throw new Error('TODO');
}

/** services: { app: ['mysql', 'redis'], mysql: [], redis: [] } */
function startupOrder(services) {
  // TODO: topological order; when several services are ready, take them alphabetically
  // TODO: unknown dependency or a cycle -> throw Error
  throw new Error('TODO');
}

Your solution

Hints

All hints revealed
Hint 1

Validate every condition first, then check each dependency against its state

Hint 2

For the order, use Kahn's algorithm: repeatedly take the services with no remaining dependencies

Hint 3

Sort the ready services and take only the first one per step, then remove it from everyone else's dependency set

Hint 4

If services remain but none is ready, you have found a cycle

Solution · python
CONDITIONS = {"service_started", "service_healthy", "service_completed_successfully"}


def can_start(deps: dict[str, str], states: dict[str, dict]) -> bool:
    """deps:   {"mysql": "service_healthy", "migrate": "service_completed_successfully"}
    states: {"mysql": {"status": "running", "health": "healthy", "exit_code": None}, ...}
    """
    for name, condition in deps.items():
        if condition not in CONDITIONS:
            raise ValueError(f"Unknown condition: {condition}")

    for name, condition in deps.items():
        state = states.get(name)
        if state is None:
            return False
        status = state.get("status")
        if condition == "service_started" and status != "running":
            return False
        if condition == "service_healthy" and not (status == "running" and state.get("health") == "healthy"):
            return False
        if condition == "service_completed_successfully" and not (status == "exited" and state.get("exit_code") == 0):
            return False
    return True


def startup_order(services: dict[str, list[str]]) -> list[str]:
    for name, deps in services.items():
        for dep in deps:
            if dep not in services:
                raise ValueError(f"{name} depends on unknown service {dep}")

    remaining = {name: set(deps) for name, deps in services.items()}
    order: list[str] = []
    while remaining:
        ready = sorted(name for name, deps in remaining.items() if not deps)
        if not ready:
            raise ValueError("Dependency cycle between: " + ", ".join(sorted(remaining)))
        current = ready[0]
        order.append(current)
        del remaining[current]
        for deps in remaining.values():
            deps.discard(current)
    return order
Solution · javascript
const CONDITIONS = ['service_started', 'service_healthy', 'service_completed_successfully'];

/**
 * deps:   { mysql: 'service_healthy', migrate: 'service_completed_successfully' }
 * states: { mysql: { status: 'running', health: 'healthy', exitCode: null }, ... }
 */
function canStart(deps, states) {
  for (const condition of Object.values(deps)) {
    if (!CONDITIONS.includes(condition)) throw new Error(`Unknown condition: ${condition}`);
  }

  return Object.entries(deps).every(([name, condition]) => {
    const s = states[name];
    if (!s) return false;
    if (condition === 'service_started') return s.status === 'running';
    if (condition === 'service_healthy') return s.status === 'running' && s.health === 'healthy';
    return s.status === 'exited' && s.exitCode === 0;
  });
}

/** services: { app: ['mysql', 'redis'], mysql: [], redis: [] } */
function startupOrder(services) {
  for (const [name, deps] of Object.entries(services)) {
    for (const dep of deps) {
      if (!(dep in services)) throw new Error(`${name} depends on unknown service ${dep}`);
    }
  }

  const remaining = new Map(Object.entries(services).map(([n, d]) => [n, new Set(d)]));
  const order = [];
  while (remaining.size > 0) {
    const ready = [...remaining].filter(([, d]) => d.size === 0).map(([n]) => n).sort();
    if (ready.length === 0) {
      throw new Error(`Dependency cycle between: ${[...remaining.keys()].sort().join(', ')}`);
    }
    const current = ready[0];
    order.push(current);
    remaining.delete(current);
    for (const d of remaining.values()) d.delete(current);
  }
  return order;
}

More from DevOps