Sub topic 9
Health checks and the unhealthy state
This chapter assumes you can run containers, read docker inspect output, and write a Dockerfile with ENTRYPOINT and CMD. It also assumes you know what an exit code means from the earlier chapters. A running container is not always a working container. Health checks let Docker test whether the application inside is actually serving requests.
What a health check adds
A container's main process can be alive while the application is broken. It may be deadlocked, stuck waiting for a database, or returning errors on every request. docker ps shows Up in all of these cases, because Docker only watches the process.
A health check is a command that Docker runs inside the container on a schedule. Docker records the result and adds a health status next to the normal state. The container stays running, and the status appears in the STATUS column, for example Up 2 minutes (healthy).
| Health status | Meaning |
|---|---|
| `starting` | The container is in its start period, or no probe has succeeded yet. |
| `healthy` | The most recent probe exited with code 0. |
| `unhealthy` | The probe has failed the configured number of times in a row. |
| none | The image and container define no health check. |
A probe's exit code decides the result. Code 0 means success, code 1 means failure, and code 2 is reserved and should not be used.
Defining a health check
You can set a health check in the Dockerfile with HEALTHCHECK:
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1Each option controls one part of the schedule:
--intervalis the time between probes. The default is 30 seconds.--timeoutis how long one probe may run before Docker counts it as failed. The default is 30 seconds.--start-periodgives slow applications time to boot. Failures during this period do not count toward--retries. A success ends the period early.--retriesis the number of consecutive failures needed to mark the containerunhealthy. The default is 3.
This example assumes curl exists in the image. The -f flag makes curl return a non-zero exit code on HTTP errors such as 500. Without it, curl exits 0 whenever it gets any response, and the check would pass for a broken application.
You can also set or override the check at run time with docker run --health-cmd, --health-interval, --health-timeout, --health-retries, and --health-start-period. Use --no-healthcheck to disable a check that the image defines. In Compose, the equivalent is the healthcheck key under a service.
How the status changes
Two details matter when debugging. First, one failed probe does not change the status. Only consecutive failures count, and a single success resets the counter. Second, unhealthy is not a final state. If the application recovers, the next successful probe returns the container to healthy.
Reading the probe results
Start with docker ps, which shows the status. Then ask for the details:
docker inspect --format '{{json .State.Health}}' webThe output contains the status, a FailingStreak counter, and a Log array with the last five probes. Each entry has a start time, an end time, an ExitCode, and the Output of the probe. The output field is usually the fastest route to the cause, because it holds the error text from the probe command.
To read only the last probe's output, pipe through a formatter:
docker inspect --format '{{(index .State.Health.Log 0).Output}}' webLog entries are ordered oldest first, so index 0 is the oldest of the stored entries. To see the newest, use index .State.Health.Log 4 once five entries exist, or print the whole array.
Common reasons a healthy application reports unhealthy
Most unhealthy containers are caused by the check itself and not by the application. Work through these causes in order.
- The tool is missing. The probe runs inside the container. If the image has no
curl, the probe fails withexecutable file not found, and the exit code is 127 or similar. Check theOutputfield, then usedocker exec web which curl. Minimal images often lackcurl, so use a tool the image already has, or add a small purpose-built probe binary. - The probe uses the wrong address. The probe runs in the container's own network namespace. It should call
localhostand the container's internal port, not a published host port. If the application listens only on a different interface or port than the probe expects, the probe fails while outside clients may still work. - The application binds to the wrong interface. An application listening on
127.0.0.1passes alocalhostprobe but is unreachable from other containers. The reverse problem is less common, but check what the process actually listens on. - The timeout is too short. A probe that takes 4 seconds against a 3 second
--timeoutalways fails. Run the probe command by hand withtimeto measure it. - The start period is too short. A slow application fails its first probes while it boots. Failures after the start period count, so the container turns
unhealthybefore it finishes starting. - The probe is too heavy. A health endpoint that queries the database or calls other services can fail when a dependency is slow. The container then looks broken because of something outside it.
To reproduce a probe, run the same command by hand inside the container:
docker exec web curl -f http://localhost:8080/health
echo $?Compare the result with the Log output. If the manual run works but the scheduled probe fails, suspect timing or load. If both fail, the application or the check is wrong.
What unhealthy does and does not do
Plain Docker does not restart or stop a container because it is unhealthy. The status is information. A restart policy such as --restart=on-failure reacts to the main process exiting, not to the health status. A container can stay unhealthy and running for days.
Orchestrators do act on it. Docker Swarm replaces unhealthy tasks. Compose can use the status to order startup with depends_on and condition: service_healthy, and a dependent service waits until the dependency is healthy. If the dependency never becomes healthy, docker compose up fails with a dependency error, and the health Log shows why.
Watching health changes
Health transitions appear as events. Stream them with the events filter from the daemon's point of view:
docker events --filter container=web --filter event=health_statusEach line shows a change to healthy or unhealthy with a timestamp. Compare these times with your application logs from docker logs --timestamps web to see what the application was doing when the check began to fail. This pairing often shows a pattern, such as failures every time a batch job runs.
A short workflow
- Run
docker psand look for(unhealthy)or(health: starting). - Read
.State.Healthwithdocker inspectand checkFailingStreakand theOutputof recent probes. - Run the probe command by hand with
docker execand check its exit code. - Read the application logs around the failure times.
- Adjust the check, the timeout, or the start period only after you know whether the application or the check is at fault.
Exercise
A container shows Up 3 minutes (unhealthy). The Dockerfile has HEALTHCHECK CMD curl -f http://localhost:8080/health || exit 1. The Output field in .State.Health.Log reads /bin/sh: curl: not found. What is wrong, and does restarting the application fix it?
Show answer
The image does not contain curl, so the probe fails every time regardless of application state. Restarting the application does not help. Either install curl in the image, or change the check to use a tool that exists there, such as wget or a small binary built for the purpose. After the fix, rebuild the image and recreate the container.
Exercise
An application takes about 40 seconds to start. The check uses --interval=10s --retries=3 and no --start-period. What happens, and how do you fix it?
Show answer
The first three probes fail during the boot, so the container becomes unhealthy after about 30 seconds, before the application is ready. It recovers to healthy once a probe succeeds. In Compose this can block dependent services or cause errors. Add --start-period=60s so early failures do not count toward the retries.