DEV Community

Cover image for Docker Compose Healthcheck and depends_on Explained
devTalk
devTalk

Posted on Originally published at dev-talk.com

Docker Compose Healthcheck and depends_on Explained

Last updated: 18 November 2026. Tested with Docker Engine 29.9.2 and Docker Compose v5.7.0. SeeHow this was checkedat the end for what was and was not run.

The classic Compose failure: docker compose up starts MySQL and your Laravel container at the same moment, the app runs php artisan migrate while MySQL is still initializing, and you get Connection refused. You added depends_on: [db], so it should have waited. It did wait, for the container to start. Docker's own documentation is explicit: on startup, Compose does not wait until a container is "ready", only until it is running.

The fix is a healthcheck on the dependency plus condition: service_healthy on the dependent. That is a few lines, but the details decide whether it works: the default timings, what happens during startup, how your check command behaves when the service half-works, and what a broken check looks like. This article walks through each one with output from real runs.

The short version

services:
  db:
    image: mysql:8.4
    environment:
      MYSQL_ROOT_PASSWORD: secret
    healthcheck:
      test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p$$MYSQL_ROOT_PASSWORD"]
      interval: 5s
      timeout: 3s
      retries: 10
      start_period: 40s

  app:
    build: .
    depends_on:
      db:
        condition: service_healthy
Enter fullscreen mode Exit fullscreen mode

Three things to notice. The healthcheck lives on the service being waited for (db), not on the one waiting. depends_on uses the long form with a condition, because the short form (depends_on: [db]) only waits for the container to start. And $$ is deliberate, for a reason covered below.

How a healthcheck decides

A container with a healthcheck has a health status next to its normal status. Per the Dockerfile reference it starts as starting, becomes healthy the first time a check passes, and becomes unhealthy after retries consecutive failures. The command's exit status is the signal: 0 means healthy, 1 means unhealthy, and 2 is reserved.

Option Default What it does
interval 30s Time between checks
timeout 30s A check running longer than this counts as failed
retries 3 Consecutive failures before unhealthy
start_period 0s Grace period; failures inside it do not count toward retries
start_interval 5s Check frequency during the start period (needs Engine 25 or newer)

The test value is either a list starting with CMD (run the command directly) or CMD-SHELL (run through /bin/sh), or a plain string, which Compose treats as CMD-SHELL. Use CMD-SHELL when you need pipes, || or environment variables.

The three conditions, side by side

depends_on accepts three conditions: service_started, service_healthy and service_completed_successfully. I ran a slow-starting db (ready after 8 seconds) with one dependent on each of the first two:

$ docker compose up -d
 Container hc1-db-1 Started
 Container hc1-app_started-1 Started       <- immediately
 Container hc1-db-1 Waiting
 Container hc1-db-1 Healthy                <- about 10 seconds later
 Container hc1-app_healthy-1 Started

$ docker compose ps
SERVICE       STATUS
app_healthy   Up 8 seconds
app_started   Up 18 seconds
db            Up 18 seconds (healthy)
Enter fullscreen mode Exit fullscreen mode

The service_started dependent started in the same second as the database. The service_healthy one started ten seconds later, when the check first passed. The third condition suits one-shot jobs like migrations. If the job exits 0, dependents start. If it exits non-zero, Compose stops and says so:

 Container hc3-migrate-1 Error service "migrate" didn't complete successfully: exit 3
 Container hc3-app-1 not started: condition "service_completed_successfully" of service "migrate" not met
service "migrate" didn't complete successfully: exit 3
Enter fullscreen mode Exit fullscreen mode

docker compose up itself exited with status 1, and the app container was left in Created state, never started.

Timing mistakes that cause failures

No start_period: the service is declared dead while it boots

With interval: 2s, retries: 2 and a service that needs 8 seconds, the check failed twice before the service was ready:

 Container hc2-db-1 Error dependency db failed to start
 Container hc2-app-1 not started: condition "service_healthy" of service "db" not met
dependency failed to start: container hc2-db-1 is unhealthy
Enter fullscreen mode Exit fullscreen mode

Two details matter. docker compose up exited with status 1, and the db container was still running, now shown as Up 4 seconds (unhealthy). Docker does not restart an unhealthy container; it only reports it. Adding start_period: 10s to the same service fixed it: failures during the start period do not count toward retries, and the dependent started as soon as the first check passed.

Long intervals make startup slow

The check first runs one interval after the container starts. With interval: 15s, a service that was ready after 2 seconds took 16 seconds for docker compose up --wait to return. Setting start_period: 30s and start_interval: 1s checks every second while starting, and the same service returned in 3 seconds. Keep the steady-state interval long if you like, and let start_interval handle startup.

Healthcheck commands that work

Each of these was run against a real server of that type, but not inside the official image (more on that at the end).

Service test What I observed
MySQL mysqladmin ping -h 127.0.0.1 -uroot -p$$MYSQL_ROOT_PASSWORD Exit 0 with "mysqld is alive"; exit 1 when nothing listens. Exit 0 even with a wrong password ("Access denied" is printed, status stays 0)
PostgreSQL pg_isready -h 127.0.0.1 -U postgres Exit 0 "accepting connections"; exit 2 "no response". It also returned 0 for a user and database that do not exist, so it checks the server, not your credentials
Redis `redis-cli ping \ grep -q PONG`
Laravel app curl -f http://localhost:8000/up Exit 0 on HTTP 200, exit 22 on a 500. See the next section

Two consequences. First, a healthcheck proves "the server answers", not "my app's credentials work", so a wrong DB_PASSWORD will still show a healthy database and fail later in the app. Second, always test your check against the failing case, not just the passing one.

Use TCP, not the local socket

The official MySQL and PostgreSQL images start a temporary server for first-run initialization. Reading their entrypoint scripts: the MySQL one starts it with --skip-networking, and the PostgreSQL one with listen_addresses=''. A check that talks over the local socket can pass during that phase, before the real server and your init scripts are done. I reproduced the idea with a MySQL server started with --skip-networking: mysqladmin ping over the socket returned "mysqld is alive" (exit 0), while the same ping with -h 127.0.0.1 failed (exit 1). That is why the examples above pass -h 127.0.0.1. I did not watch the official images initialize, so treat this as a precaution grounded in their source, not an observed failure.

Laravel: /up does not check your database

Laravel 13 ships a health route at /up. Its docs say it returns 200 if the app booted without exceptions, and 500 otherwise. That is a boot check. I pointed a test app at an unreachable database port and requested it:

DB reachable             : /up -> HTTP 200, curl -f exit 0
DB unreachable (port 1)  : /up -> HTTP 200, curl -f exit 0
Enter fullscreen mode Exit fullscreen mode

The container looked healthy with no database behind it. The same docs describe the way to add real checks: the route dispatches an Illuminate\Foundation\Events\DiagnosingHealth event, and a listener that throws turns the response into a 500. A one-query check in AppServiceProvider::boot():

use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;

public function boot(): void
{
    Event::listen(DiagnosingHealth::class, function () {
        DB::select('select 1');
    });
}
Enter fullscreen mode Exit fullscreen mode
DB reachable             : /up -> HTTP 200, curl -f exit 0
DB unreachable (port 1)  : /up -> HTTP 500, curl -f exit 22
Enter fullscreen mode Exit fullscreen mode

Decide deliberately whether you want this. A health route that depends on the database tells a load balancer to pull the app out the moment the database blips. For gating Compose startup, that is what you want. For a liveness-style check, keep /up light. The official PHP images include curl (the Dockerfiles install it as a runtime dependency), so curl -f works without adding packages, but confirm that for the base image you use.

A complete Laravel stack

This file runs MySQL, Redis, a one-shot migration job, the app and a queue worker. Migrations run in their own service so they run once, not once per app replica:

services:
  db:
    image: mysql:8.4
    environment:
      MYSQL_DATABASE: laravel
      MYSQL_ROOT_PASSWORD: secret
    volumes:
      - dbdata:/var/lib/mysql
    healthcheck:
      test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p$$MYSQL_ROOT_PASSWORD"]
      interval: 10s
      timeout: 3s
      retries: 5
      start_period: 40s
      start_interval: 2s

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

  migrate:
    build: .
    command: php artisan migrate --force
    environment: &laravel-env
      DB_HOST: db
      DB_DATABASE: laravel
      DB_USERNAME: root
      DB_PASSWORD: secret
      REDIS_HOST: redis
    depends_on:
      db:
        condition: service_healthy

  app:
    build: .
    command: php artisan serve --host=0.0.0.0 --port=8000
    ports:
      - "8000:8000"
    environment: *laravel-env
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
      migrate:
        condition: service_completed_successfully
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/up"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 20s
      start_interval: 2s

  queue:
    build: .
    command: php artisan queue:work --tries=3
    environment: *laravel-env
    depends_on:
      redis:
        condition: service_healthy
      migrate:
        condition: service_completed_successfully

volumes:
  dbdata:
Enter fullscreen mode Exit fullscreen mode

php artisan serve is a development convenience; in production you would run PHP-FPM behind a web server, with the same dependency pattern. The password in the file is a placeholder, so move real secrets to an .env file or Docker secrets.

The service_completed_successfully gate only works if the job fails loudly. I ran php artisan migrate --force against a reachable database (exit 0, "Nothing to migrate") and an unreachable one (exit 1, SQLSTATE[HY000] [2002] Connection refused), so a failed migration blocks the app as intended.

I could not run this exact file, because the images are not reachable from my environment. To check the dependency graph, I ran the same topology with stand-in containers and timings (db ready after 6 seconds, redis after 1, a 2-second migration). The order came out as expected:

db, redis   started at 0s
migrate     started after db was healthy        (about 7s)
queue, app  started after migrate exited        (about 9-10s)
Enter fullscreen mode Exit fullscreen mode

Compose-file gotchas

$$ versus $: a broken check that reports healthy

Compose interpolates ${VAR} from your host environment when it reads the file. To pass a literal $ through to the container's shell, write $$. Forget it and the variable is replaced with an empty string before the container ever sees it. I tested a check test -f ${CHECK_FILE} against one written test -f $${CHECK_FILE}, where the file never exists:

SERVICE   STATUS
broken    Up 6 seconds (healthy)
correct   Up 6 seconds (unhealthy)
Enter fullscreen mode Exit fullscreen mode

Compose warned that CHECK_FILE was not set, but the broken version ran test -f with no argument, which a POSIX shell treats as true. A typo in your healthcheck can make it always pass. Run docker compose config and read the final test value.

Optional dependencies and restarts

Two long-syntax fields are useful. required: false turns a failed dependency into a warning instead of an error. With an unhealthy cache marked this way, up printed optional dependency "cache" failed to start, exited 0, and started the app. restart: true restarts the dependent when Compose restarts the dependency: after docker compose restart db, the app container was restarted too. Per the docs, this applies to explicit Compose operations, not to a container the runtime restarts after a crash.

Healthchecks gate startup, nothing more

Compose evaluates depends_on when it creates services. If the database goes down later, your app is not stopped or restarted by the condition. Keep connection retry logic in the application, and treat the healthcheck as a startup gate and a status indicator.

Debugging a check that will not go healthy

docker compose ps
docker inspect --format '{{json .State.Health}}' <container> | python3 -m json.tool
Enter fullscreen mode Exit fullscreen mode

The second command returns the status, the failing streak and a log of recent checks with exit codes and output. In my runs the log held the last five checks. Per the Dockerfile reference, output from stdout and stderr is stored, up to 4096 bytes. Note that mysqladmin prints a warning to stderr when you pass the password on the command line, so expect to see it in this log. I saw that warning in my local run but did not inspect it inside a container.

Alternatives

  • Retry in the entrypoint. A script that loops until the database accepts connections works on any Compose version and survives later restarts. It adds code to maintain, and it does not show status in docker compose ps.
  • Application retries. A worker that reconnects on failure handles both startup and mid-run outages. Use it in addition to a healthcheck, not instead of one.

Related Dev Talk articles

Frequently asked questions

Why does depends_on not wait for MySQL to be ready?

By default it waits for the dependency container to start. Add a healthcheck to the database and use condition: service_healthy in the dependent service.

Does Docker restart an unhealthy container?

Not in my tests: the unhealthy database stayed running with an (unhealthy) status. Restarting based on health needs something else, such as an orchestrator.

What is the difference between start_period and interval?

start_period is a grace window where failures do not count toward retries. interval is the steady-state spacing between checks. During the start period, checks run at start_interval instead.

Do I need Compose v2?

The long-form fields have minimum versions in the Compose docs: restart in 2.17.0, required in 2.20.0, and the duration-style healthcheck fields from 2.20.2. I tested Compose v5.7.0 only.

update log

  • 18 November 2026: first published.
  • To recheck on each update: the healthcheck defaults, whether the official MySQL and PostgreSQL entrypoints still start temporary servers without TCP, and whether the Laravel skeleton changes the /up behavior.

Sources


Originally published on DEV Talk.

Top comments (0)