TExcelTAD
Home › Docker Compose › Healthchecks

Healthchecks

A container being running only means its main process hasn't exited. It says nothing about whether Postgres accepts connections yet, or whether your API answers requests. A healthcheck is a small command that Docker runs inside the container at regular intervals; its exit code turns the container's status into starting, healthy or unhealthy. Compose uses that status for startup order and up --wait, and you see it in docker compose ps. (The Dockerfile side, HEALTHCHECK, is covered in HEALTHCHECK and LABEL.)

text
  every interval:   run test ──▶ exit 0 ──▶ healthy (failure counter reset)
                              └▶ exit 1 or timeout ──▶ failures += 1 ──▶ failures == retries ──▶ unhealthy
  during start_period: failures don't count; probes run every start_interval; first success ⇒ healthy

The healthcheck keys

Key Default Meaning
test from the image's HEALTHCHECK, if any the command to run
interval 30s time between checks once started
timeout 30s a check that takes longer counts as failed
retries 3 consecutive failures before unhealthy
start_period 0s grace period after start: failures don't count
start_interval 5s time between checks during the start period
disable false true turns off the image's healthcheck

A Compose healthcheck replaces the image's HEALTHCHECK field by field.

The test command and its normal form

test comes in three shapes. Compose normalises the first one:

compose · try it yourself
services:
  shell-string:
    image: shop/api:1.4
    healthcheck:
      test: curl -fsS http://localhost:8000/health || exit 1
  exec-form:
    image: postgres:18
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
  shell-form:
    image: redis:8
    healthcheck:
      test: ["CMD-SHELL", "redis-cli ping | grep -q PONG"]
name: demo
services:
  exec-form:
    image: postgres:18
    networks:
      default: null
    healthcheck:
      test:
        - CMD
        - pg_isready
        - -U
        - postgres
  shell-form:
    image: redis:8
    networks:
      default: null
    healthcheck:
      test:
        - CMD-SHELL
        - redis-cli ping | grep -q PONG
  shell-string:
    image: shop/api:1.4
    networks:
      default: null
    healthcheck:
      test:
        - CMD-SHELL
        - curl -fsS http://localhost:8000/health || exit 1
networks:
  default:
    name: demo_default
  • A plain string becomes CMD-SHELL: it runs through /bin/sh -c, so ||, pipes and variables work. (Unlike command, where a string is merely split into words.)
  • ["CMD", …] runs the program directly, with no shell. Faster, but no shell syntax.
  • ["CMD-SHELL", "…"] is the explicit shell form.

The command runs inside the container, so the tools must exist there. Many slim images have no curl; use wget -qO- … (BusyBox images), the language runtime (python -c "…"), or a tiny health binary in your image.

Durations

Durations are written like Go durations: a number with a unit, us, ms, s, m or h, combinable as 1m30s. Compose normalises them:

compose · try it yourself
services:
  api:
    image: shop/api:1.4
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request as u; u.urlopen('http://localhost:8000/health')"]
      interval: 90s
      timeout: 1500ms
      retries: 5
      start_period: 0.5m
      start_interval: 2s
name: demo
services:
  api:
    image: shop/api:1.4
    networks:
      default: null
    healthcheck:
      test:
        - CMD
        - python
        - -c
        - import urllib.request as u; u.urlopen('http://localhost:8000/health')
      timeout: 1.5s
      interval: 1m30s
      retries: 5
      start_period: 30s
      start_interval: 2s
networks:
  default:
    name: demo_default

90s became 1m30s, 1500ms became 1.5s, and 0.5m became 30s. Spelled-out units are rejected:

compose · try it yourself
services:
  api:
    image: shop/api:1.4
    healthcheck:
      test: ["CMD", "true"]
      interval: 5 seconds
decoding failed due to the following error(s):

'services[api].healthcheck.interval' time: unknown unit " seconds" in duration "5 seconds"

Turning healthchecks off

Some images ship a HEALTHCHECK you don't want (for example, a heavy check in a test environment). Two ways to switch it off:

compose · try it yourself
services:
  quiet:
    image: shop/api:1.4
    healthcheck:
      disable: true
  also-quiet:
    image: shop/api:1.4
    healthcheck:
      test: ["NONE"]
name: demo
services:
  also-quiet:
    image: shop/api:1.4
    networks:
      default: null
    healthcheck:
      test:
        - NONE
  quiet:
    image: shop/api:1.4
    networks:
      default: null
    healthcheck:
      disable: true
networks:
  default:
    name: demo_default

Good checks for common services

Service Test Note
PostgreSQL ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"] $ so the container's variables are used
MySQL / MariaDB ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1"] localhost would use the socket during init
Redis ["CMD", "redis-cli", "ping"] add -a or REDISCLI_AUTH if a password is set
HTTP API ["CMD", "wget", "-qO-", "http://127.0.0.1:8000/health"] a cheap endpoint that checks its own dependencies sparingly
RabbitMQ ["CMD", "rabbitmq-diagnostics", "-q", "ping"]

A good health endpoint answers quickly and reflects whether this service can do its job. Avoid checks that call other services' health endpoints in a chain: one slow database then marks everything unhealthy at once.

Watching health

bash
$ docker compose up -d
$ docker compose ps
NAME        IMAGE         COMMAND                  SERVICE   CREATED         STATUS                            PORTS
shop-db-1   postgres:18   "docker-entrypoint.s…"   db        4 seconds ago   Up 3 seconds (health: starting)   5432/tcp
$ docker compose ps
NAME        IMAGE         COMMAND                  SERVICE   CREATED          STATUS                    PORTS
shop-db-1   postgres:18   "docker-entrypoint.s…"   db        12 seconds ago   Up 11 seconds (healthy)   5432/tcp
$ docker inspect --format '{{json .State.Health.Log}}' shop-db-1 | head -c 160
[{"Start":"2026-10-18T09:31:02.5Z","End":"2026-10-18T09:31:02.6Z","ExitCode":0,"Output":"/var/run/postgresql:5432 - accepting connections\n"}

(Sample output.) docker inspect keeps the output of the last few probes, the first place to look when a container is stuck in unhealthy. An unhealthy container is not restarted automatically by plain Docker or Compose; it just reports the state. (Swarm and Kubernetes do replace unhealthy tasks and pods.)

A model of the health state machine

The model replays a list of probe results with Docker's rules: during start_period, failures are ignored and probes run every start_interval; the first success ends the start period; afterwards, retries consecutive failures make the container unhealthy and any success makes it healthy again.

python · try it yourself
def simulate(results, interval=10, start_period=0, start_interval=5, retries=3):
    t, status, failures, starting = 0, "starting", 0, start_period > 0
    timeline = []
    for ok in results:
        t += start_interval if starting and t < start_period else interval
        in_grace = starting and t <= start_period
        if ok:
            status, failures, starting = "healthy", 0, False
        elif not in_grace:
            starting = False
            failures += 1
            if failures >= retries:
                status = "unhealthy"
        timeline.append(f"t={t:>3}s {'ok  ' if ok else 'FAIL'} -> {status}{' (grace)' if in_grace and not ok else ''}")
    return timeline

print("A database that needs ~20s to start, start_period 30s:")
for line in simulate([False, False, False, False, True, True], start_period=30):
    print("  " + line)

print("Same database without a start_period:")
for line in simulate([False, False, False, True]):
    print("  " + line)

print("An API that breaks later:")
for line in simulate([True, False, False, True, False, False, False]):
    print("  " + line)
A database that needs ~20s to start, start_period 30s:
  t=  5s FAIL -> starting (grace)
  t= 10s FAIL -> starting (grace)
  t= 15s FAIL -> starting (grace)
  t= 20s FAIL -> starting (grace)
  t= 25s ok   -> healthy
  t= 35s ok   -> healthy
Same database without a start_period:
  t= 10s FAIL -> starting
  t= 20s FAIL -> starting
  t= 30s FAIL -> unhealthy
  t= 40s ok   -> healthy
An API that breaks later:
  t= 10s ok   -> healthy
  t= 20s FAIL -> healthy
  t= 30s FAIL -> healthy
  t= 40s ok   -> healthy
  t= 50s FAIL -> healthy
  t= 60s FAIL -> healthy
  t= 70s FAIL -> unhealthy

With a start_period, slow starters reach healthy quickly (probes every 5 s) and without false alarms. Without one, the same database is marked unhealthy before it is ready, and anything waiting for it with condition: service_healthy gives up. The third run shows recovery: a single success resets the counter.

Learn more: depends_on & Startup Order · Restart Policies · Swarm healthchecks · Kubernetes probes

Test yourself

What does test: curl -f http://localhost/ || exit 1 (a plain string) become?

  1. ["CMD", "curl", …] without a shell
  2. ["CMD-SHELL", "curl -f http://localhost/ || exit 1"]
  3. An error: test must be a list
  4. ["NONE"]

What happens to failed probes during start_period?

  1. They count towards retries
  2. They are ignored; the first success marks the container healthy
  3. The container is restarted
  4. Compose stops the project

In plain Compose, what happens to a container that becomes unhealthy?

  1. It is restarted automatically
  2. It is removed
  3. Nothing by itself: its status shows unhealthy, and dependents waiting on service_healthy won't start
  4. It is moved to another host