Home DockerDocker Compose Healthchecks: Build Self-Healing Containers

Docker Compose Healthchecks: Build Self-Healing Containers

by Knowledge Base Linux
Docker Compose Healthchecks — Docker Compose Healthchecks: Build Self-Healing Containers

The Problem: Started Is Not the Same as Ready – Docker Compose Healthchecks

Every Docker Compose user has hit this: docker compose up finishes, the app container tries to reach the database, and crashes — because the database container was started but not yet ready to accept connections. The classic depends_on directive only controls startup order; it does not wait for a service to actually work. A docker compose healthcheck closes that gap. It tells Docker how to probe each service, reports healthy or unhealthy status, and lets dependent services wait for real readiness. Combined with restart policies, healthchecks are the foundation of self-healing container stacks.

Docker Compose healthcheck status showing healthy containers in docker compose ps output

Prerequisites – Docker Compose Healthchecks

You need Docker Engine with the Compose v2 plugin installed (docker compose version should report v2.x), basic familiarity with a Compose file, and a terminal on a Linux host. If you are new to multi-container setups, our Docker Compose LEMP stack guide is a good warm-up. When containers misbehave, the techniques in troubleshooting Docker logs pair well with what follows. No extra tooling is required — the docker compose healthcheck feature is built into Docker Engine and the Compose specification.

What Is a Docker Compose Healthcheck?

A healthcheck is a command Docker runs inside a container on a schedule. Based on the exit code, the container gets a health status:

starting — checks are running but the service has not passed yet (or is still in its grace period).
healthy — the check command exited 0.
unhealthy — the check failed more times in a row than retries allows.

You can watch these states live with docker ps, which shows e.g. Up 2 minutes (healthy) next to each container. The status is informational by itself — Docker does not restart an unhealthy container on its own — but Compose and orchestrators can act on it, which is exactly what makes self-healing possible.

Docker Compose Healthcheck Syntax, Field by Field

A docker compose healthcheck block lives under a service in your Compose file. Here is the full anatomy from the official Compose file reference:

services:
  web:
    image: nginx:alpine
    healthcheck:
      test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost/"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 15s

test — the probe command, in one of three forms. CMD runs a binary directly with no shell: ["CMD", "redis-cli", "ping"]. CMD-SHELL runs through /bin/sh -c, so shell features like && and environment variables work: ["CMD-SHELL", "pg_isready -U postgres"]. ["NONE"] disables a healthcheck inherited from the image.

interval — how often to run the check (default 30s; 5–10s is typical for services you care about). timeout — how long one check may run before it counts as failed (default 30s). retries — consecutive failures before the container is marked unhealthy (default 3).

start_period — a grace period after container start during which failures do not count toward retries. Essential for databases that need 10–30 seconds to initialize. Newer Docker versions also support start_interval, which sets a faster check cadence specifically during the start period.

disable — set disable: true to turn off a healthcheck without deleting the block.

Step-by-Step: Add Healthchecks to a Real Stack

Let us build a small app-plus-database stack where every service is health-checked and startup is properly gated.

Step 1: Health-check the database with its native tool

Every docker compose healthcheck for a database should use the readiness utility each database ships with. For PostgreSQL it is pg_isready; for Redis, redis-cli ping; for MySQL/MariaDB, mysqladmin ping:

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

  cache:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

Note that CMD runs without a shell, so it cannot expand variables — use CMD-SHELL when you need ${POSTGRES_USER} inside the container. And remember Compose interpolates ${VAR} in the file itself, so write $${VAR} to defer expansion to the container shell.

Step 2: Health-check your own web service

For an HTTP service, the docker compose healthcheck usually probes an endpoint. Add a lightweight /health route to your app if you can; otherwise check the root path:

  api:
    build: ./api
    healthcheck:
      test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1"]
      interval: 10s
      timeout: 5s
      retries: 3
      start_period: 30s
    ports:
      - "3000:3000"

Prefer wget over curl in Alpine-based images, since curl is often not installed. The || exit 1 guarantees a non-zero exit when the probe fails, which is what Docker counts on.

Step 3: Gate startup with depends_on and service_healthy

Now make the app wait for real readiness, not just container startup:

  api:
    build: ./api
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_healthy

The long syntax of depends_on with condition: service_healthy holds the api service until both dependencies report healthy. Two other conditions exist: service_started (the old short-syntax behavior — only waits for the container to run) and service_completed_successfully (for one-shot tasks like migrations that must exit 0). This long syntax requires Compose v2 — check with docker compose version and upgrade if your plugin predates it.

Step 4: Bring the stack up and verify

docker compose up -d
docker compose ps

docker compose ps shows a health column per service. Watch a database go from starting to healthy, and confirm the app container only starts after its dependencies turn healthy. For detail on recent check output, inspect the container state:

docker inspect --format='{{json .State.Health}}' myproject-db-1 | python3 -m json.tool

Making Containers Self-Healing: Healthchecks Plus Restart Policies

A common misconception: Docker does not automatically restart a container just because a docker compose healthcheck reports it unhealthy. The status is a signal — you decide what acts on it. A genuinely self-healing Compose stack combines three layers:

Layer 1: restart policy. restart: unless-stopped (or always) recovers containers that crash outright. Note that on-failure only reacts to non-zero exits, not to unhealthy status — for full coverage, prefer unless-stopped.

services:
  api:
    build: ./api
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1"]
      interval: 10s
      timeout: 5s
      retries: 3
      start_period: 30s

Layer 2: gated startup. The docker compose healthcheck combined with the depends_on conditions from Step 3 ensures a restarted stack comes back in the right order, with the app waiting for a truly ready database instead of racing it.

Layer 3: act on unhealthy status. For automatic restarts of containers that stay up but report unhealthy (a hung web process, a wedged database), add a small watcher container such as the well-known autoheal image, which polls the Docker socket and restarts containers labeled for healing. Label the services you want watched and the watcher handles the rest — that closes the loop from “detected sick” to “restarted clean.”

Together, these layers mean crashed containers restart, slow dependencies are waited on, and hung-but-running services get recycled — a self-healing stack built entirely from standard Compose primitives.

Monitoring Health Status in Production

Once every service carries a docker compose healthcheck, make health status part of your routine checks. docker compose ps gives the quick overview; for alerting, script against docker inspect:

docker inspect --format '{{.Name}} {{.State.Health.Status}}' $(docker compose ps -q)

Anything stuck in starting far past its start_period, or flapping between healthy and unhealthy, deserves investigation before it becomes an outage. Pipe this into your existing monitoring — the same Zabbix or Prometheus agent checks you run for host metrics can run this command on Docker hosts.

Troubleshooting Docker Compose Healthchecks

Docker compose healthcheck fails immediately on a fresh database. The start_period is too short or missing. PostgreSQL on slow disks can need 30 seconds or more for first-time initialization — set start_period: 60s and retries: 5 generously for databases.

“executable file not found” in check output. The probe binary is not in the image. Slim and Alpine images often lack curl; use wget, or switch the test to a CMD form calling a binary you know exists. Check with docker compose exec db which pg_isready.

Environment variables do not expand in the check. You used the CMD form, which bypasses the shell. Switch to CMD-SHELL, and remember to escape Compose-level interpolation with $$ when the variable should be resolved inside the container.

depends_on condition seems ignored. You are running an old Compose release. The long syntax with condition needs Compose v2 — the legacy Python docker-compose v1 does not support it in all file formats. Upgrade the plugin and remove any obsolete version: key from the file.

Service marked unhealthy but the app works fine. The probe is stricter than reality — for example, checking / on an app that returns 404 there. Point the check at a dedicated /health endpoint that verifies downstream dependencies, so healthy actually means “ready to serve.”

Conclusion

A docker compose healthcheck turns “the container is running” into “the service actually works” — and that distinction is the difference between stacks that wake you at 3 AM and stacks that heal themselves. Define a docker compose healthcheck for every service using native readiness tools, give databases a generous start_period, gate dependents on service_healthy, and layer a restart policy underneath. Your future self, asleep through the night while Compose restarts a wedged container, will appreciate it.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.