Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 111 ยท Dockerfiles

HEALTHCHECK

Learn how the Docker HEALTHCHECK instruction works: options, exit codes, the starting, healthy and unhealthy states, docker ps status, and healthchecks in Compose.

A container that is "running" is not necessarily working. A web server can be stuck in an infinite loop, a database can still be recovering after a crash, an app can have lost its connection pool. To Docker, all of these look the same: the main process is alive, so the container is Up. A healthcheck closes that gap. It is a small command that Docker runs inside the container at regular intervals; its exit code tells Docker whether the application is actually healthy.

In this lesson you will learn the HEALTHCHECK instruction, its options, how Docker turns exit codes into the starting, healthy and unhealthy states, how to read the results, what a healthcheck can and cannot do, and how the same idea looks in Compose. Every output below comes from real containers.

Adding a healthcheck

The simplest healthcheck is one line in the Dockerfile:

DOCKERFILE
FROM nginx:1.27-alpine
HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=2 \
  CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1

Everything after the word CMD is the probe: a command that must exit with 0 if the app is healthy and 1 if it is not. Here wget requests the home page and discards the body; wget exits non-zero if the connection fails or the server returns an error status, and || exit 1 makes the result explicit.

Build it and start a container. Watch the status in docker ps:

CONSOLE
$ docker build -t hc-demo .
$ docker run -d --name web hc-demo
$ docker ps --filter name=web --format '{{.Names}} {{.Status}}'
web Up 1 second (health: starting)
$ docker ps --filter name=web --format '{{.Names}} {{.Status}}'
web Up 8 seconds (healthy)

A new container starts in the starting state. After the first successful probe it becomes healthy. The status is shown in parentheses in the STATUS column of docker ps, and is also available from docker inspect:

CONSOLE
$ docker inspect web --format '{{json .Config.Healthcheck}}'
{"Test":["CMD-SHELL","wget -q -O /dev/null http://127.0.0.1/ || exit 1"],"Interval":5000000000,"Timeout":3000000000,"StartPeriod":5000000000,"Retries":2}

(Durations are stored in nanoseconds: 5000000000 is five seconds.) Notice CMD-SHELL: when you write a plain command after HEALTHCHECK CMD, Docker runs it through /bin/sh -c, the same as shell form in CMD and ENTRYPOINT. You can use the exec form instead to avoid the shell: HEALTHCHECK CMD ["wget", "-q", "-O", "/dev/null", "http://127.0.0.1/"].

The options

HEALTHCHECK takes these options before CMD:

Option Default Meaning
--interval=DURATION 30s Time between probes. The first probe runs one interval after the container starts.
--timeout=DURATION 30s If a probe runs longer than this, it counts as a failure.
--start-period=DURATION 0s Grace time for slow starters. Failures during it do not count toward retries, but a success ends it early.
--start-interval=DURATION 5s Probe frequency during the start period (Docker 25 and newer).
--retries=N 3 Number of consecutive failures before the container is unhealthy.

Durations accept units like 500ms, 5s, 1m.

Exit codes

The probe's exit code decides everything:

  • 0 means success, the container is healthy.
  • 1 means failure, the container is unhealthy (once retries consecutive failures happened).
  • 2 is reserved. Do not use it in your own probes.

Anything else counts as a failure too, but stick to 0 and 1.

The three states

TEXT
   container starts
          |
          v
   +-------------+   probe passes    +-----------+
   |  starting   | ----------------> |  healthy  |
   +-------------+                   +-----------+
          |                            |      ^
          | N failures after           |      | one pass
          | the start period           v      |
          |                       +-------------+
          +---------------------> |  unhealthy  |
                                  +-------------+
  • starting: no successful probe yet and the failure count has not reached retries (failures during --start-period are ignored).
  • healthy: the latest probe succeeded.
  • unhealthy: retries probes in a row failed. A single later success makes the container healthy again.

Docker keeps a failing streak count and the last five probe results. Let us make a container that becomes unhealthy on purpose. This one uses the run-time flags (more on them in a moment) so we can flip the state by creating a file:

CONSOLE
$ docker run -d --name probe \
    --health-cmd 'test -f /tmp/ready' \
    --health-interval 2s --health-retries 2 --health-timeout 2s \
    alpine:3.22 sleep 600
$ docker ps --filter name=probe --format '{{.Status}}'
Up 1 second (health: starting)
$ docker ps --filter name=probe --format '{{.Status}}'
Up 7 seconds (unhealthy)
$ docker inspect probe --format '{{.State.Health.Status}} streak={{.State.Health.FailingStreak}}'
unhealthy streak=3
$ docker exec probe touch /tmp/ready
$ docker ps --filter name=probe --format '{{.Status}}'
Up 12 seconds (healthy)

The file did not exist, so test -f exited 1 each time, and after two failures (--health-retries 2) the status flipped to unhealthy. Creating the file made the next probe pass and the status went straight back to healthy. The container stayed up the whole time.

What the probe sees: output and timeouts

Docker stores up to 4,096 bytes of the probe's output (stdout and stderr) with each result, which makes failures much easier to diagnose. Try a probe that explains itself:

CONSOLE
$ docker run -d --name loud \
    --health-cmd 'sh -c "echo probe says: disk almost full; exit 1"' \
    --health-interval 2s --health-retries 1 alpine:3.22 sleep 600
$ docker inspect loud --format '{{range .State.Health.Log}}exit={{.ExitCode}} out={{printf "%q" .Output}}{{"\n"}}{{end}}'
exit=1 out="probe says: disk almost full\n"
exit=1 out="probe says: disk almost full\n"

If a probe takes longer than --timeout, Docker stops waiting and records a special result:

CONSOLE
$ docker run -d --name slow --health-cmd 'sleep 5' --health-timeout 1s \
    --health-interval 2s --health-retries 1 alpine:3.22 sleep 600
$ docker inspect slow --format '{{.State.Health.Status}} {{range .State.Health.Log}}exit={{.ExitCode}} out={{printf "%q" .Output}}{{"\n"}}{{end}}'
unhealthy exit=-1 out="Health check exceeded timeout (1s)"
exit=-1 out="Health check exceeded timeout (1s)"

Whenever the status changes, the daemon emits an event, which monitoring tools can follow with docker events:

CONSOLE
$ docker events --filter container=loud --filter event=health_status --format '{{.Action}}'
health_status: unhealthy

Filtering by health

docker ps can filter on the health state, which is handy in scripts and for finding sick containers quickly:

CONSOLE
$ docker ps --filter health=unhealthy --format '{{.Names}}'
$ docker ps --filter health=healthy --format '{{.Names}}'
probe

The first command printed nothing (no unhealthy containers at that moment), the second listed probe.

Overriding and disabling healthchecks

The Dockerfile value is only a default. At run time you can change any option, replace the command, or turn it off:

CONSOLE
$ docker run -d --name tuned --health-interval 30s hc-demo
$ docker inspect tuned --format '{{json .Config.Healthcheck}}'
{"Test":["CMD-SHELL","wget -q -O /dev/null http://127.0.0.1/ || exit 1"],"Interval":30000000000,"Timeout":3000000000,"StartPeriod":5000000000,"Retries":2}
$ docker run -d --name quiet --no-healthcheck hc-demo
$ docker ps --filter name=quiet --format '{{.Status}}'
Up 3 seconds

The matching flags are --health-cmd, --health-interval, --health-timeout, --health-retries, --health-start-period and --health-start-interval. With --no-healthcheck, no status appears at all.

In a Dockerfile, a child image can remove a healthcheck it inherited from its parent:

DOCKERFILE
FROM hc-demo
HEALTHCHECK NONE
CONSOLE
$ docker image inspect hc-demo-none --format '{{json .Config.Healthcheck}}'
{"Test":["NONE"]}

A Dockerfile can contain only one HEALTHCHECK; if there are several, the last one wins. The base image nginx:1.27-alpine has no healthcheck of its own (its Config.Healthcheck is null), which is typical. Few official images ship one, so you usually add it yourself.

What a healthcheck does and does not do

This is where beginners get surprised, so read it twice.

Docker does not restart an unhealthy container. The probe changes a label on the container and emits an event; that is all. In our probe experiment, the container stayed up while it was unhealthy. Restart policies (--restart) react to the process exiting, not to health.

What does act on health:

  • Docker Swarm replaces unhealthy service tasks.
  • Compose can make one service wait until another is healthy with depends_on: condition: service_healthy (see below).
  • Load balancers and proxies that read container health (Traefik, some orchestrators) can stop sending traffic.
  • You: a monitoring script or auto-heal container can restart containers whose status is unhealthy.
  • Kubernetes ignores Docker healthchecks. It has its own liveness and readiness probes, configured in the Pod spec.

Because a healthcheck makes a decision for a person or tool, make it answer a clear question. "Can this container do its job right now?" is a good one.

Writing good probes

A healthcheck is code that runs every few seconds for the life of the container, so treat it with care.

  1. Test the real thing, cheaply. For a web app, request a lightweight /health endpoint that checks its critical dependencies. For PostgreSQL, pg_isready does the job. For Redis, redis-cli ping.
  2. Use a tool that exists in the image. curl is common in the examples you will find online but is missing from many slim images and from scratch and distroless images. Check what you have (wget on Alpine's BusyBox, or a tiny built-in command of your own app such as ./server --healthcheck). A probe that cannot run is always a failure, which looks like a sick app.
  3. Probe 127.0.0.1 inside the container, not an external address. Binding matters: an app listening only on 127.0.0.1 still passes this probe, while an app that never opened the port fails it.
  4. Keep it fast and quiet. Keep the timeout shorter than the interval. A heavy probe (a full database query, a big HTTP page) puts constant load on your app.
  5. Do not make it too sensitive. Flapping between healthy and unhealthy because of one slow response helps nobody. Use retries of 3 or more, and a start-period that covers a normal startup.
  6. Keep secrets out of it. The probe command and its output are visible in docker inspect.

A typical HTTP service, using the app's own endpoint:

DOCKERFILE
HEALTHCHECK --interval=15s --timeout=3s --start-period=20s --retries=3 \
  CMD wget -q -O /dev/null http://127.0.0.1:3000/healthz || exit 1

Healthchecks in Compose

Compose uses the same idea with a healthcheck: key per service. It overrides whatever the image defines. Here is a database and a web server; the web service only starts after the database is healthy.

YAML
services:
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_PASSWORD: example
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 3s
      timeout: 3s
      retries: 5
      start_period: 5s
  web:
    image: nginx:1.27-alpine
    depends_on:
      db:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/"]
      interval: 3s
      timeout: 2s
      retries: 3

test is either a list starting with CMD (exec form, no shell), CMD-SHELL (shell form, one string) or NONE. Running it:

CONSOLE
$ docker compose up -d
 Network demo_default Created
 Container demo-db-1 Creating
 Container demo-db-1 Created
 Container demo-web-1 Creating
 Container demo-web-1 Created
 Container demo-db-1 Starting
 Container demo-db-1 Started
 Container demo-db-1 Waiting
 Container demo-db-1 Healthy
 Container demo-web-1 Starting
 Container demo-web-1 Started
$ docker compose ps
NAME         SERVICE   STATUS                            PORTS
demo-db-1    db        Up 11 seconds (healthy)           5432/tcp
demo-web-1   web       Up 2 seconds (health: starting)   80/tcp

Compose waited at Container demo-db-1 Waiting until the database reported Healthy, and only then started web. Without the condition, depends_on alone would only wait for the container to start, not for PostgreSQL to accept connections. (The docker compose ps output above is shortened to the columns we need.) Startup Order and Health explores this pattern in depth, and Services in Compose covers the other service keys.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A container's HEALTHCHECK fails three times in a row, and the status becomes unhealthy. What does Docker do to the container by default?

    A healthcheck only changes the reported status and emits an event. Restart policies react to process exit, not to health. Swarm, Compose conditions and monitoring tools are what act on it.
  2. 2. What do the exit codes of a healthcheck command mean?

    Exit code 0 is success, 1 is failure, and 2 is reserved by Docker. Output is only recorded to help you diagnose.
  3. 3. What is --start-period for?

    During the start period failures are not counted, so an app that needs 20 seconds to boot is not marked unhealthy while it warms up. A success ends the period early.
  4. 4. In Compose, you want web to start only when the db service accepts connections. Which setup does that?

    Plain depends_on waits only for the container to start. The service_healthy condition waits until the healthcheck reports healthy.
  5. 5. A probe uses curl, but the container's image is a minimal one without curl. What will you see?

    The command cannot be executed, which counts as a failure. Use a tool the image has, or add a small health command to your own app.

Summary

  • HEALTHCHECK CMD <probe> runs a command inside the container at an interval; exit code 0 means healthy, 1 means unhealthy.
  • A container goes starting โ†’ healthy, and becomes unhealthy after --retries consecutive failures (defaults: interval 30s, timeout 30s, start-period 0s, retries 3).
  • See the status in docker ps, details and the last results (with output) in docker inspect, changes in docker events, and filter with docker ps --filter health=unhealthy.
  • Override or disable it at run time with --health-* flags and --no-healthcheck; HEALTHCHECK NONE disables an inherited one.
  • Docker itself does not restart unhealthy containers. Swarm, Compose depends_on conditions, proxies and your own monitoring act on the status; Kubernetes uses its own probes.
  • Use a cheap probe with a tool that exists in the image, test the real app on 127.0.0.1, and allow a start period.
  • In Compose, write healthcheck: with test, interval, timeout, retries and start_period, and combine it with condition: service_healthy.

Next: The Build Cache