Automating Docker Container Health Checks
A running container is not necessarily a working one. The process inside can be alive while the application has deadlocked, lost its database connection or stopped accepting requests. docker ps would still show the container as Up, and the restart policy would do nothing, because the process has not exited. A health check closes that gap: it is a command that Docker runs inside the container at regular intervals to ask the application whether it is actually doing its job.
This lesson explains how Docker health checks work, how to write a reliable check command in Bash, how scripts read the health state, and how to build automation on top of it: waiting until containers are ready, and a watcher that restarts containers when they become unhealthy, with a limit so that a container that cannot be repaired by a restart is reported instead of being restarted forever.
How Docker Runs a Health Check
A health check is defined by a command and four timing settings. Docker starts the command inside the container (with docker exec-like semantics, as the container's user and with its environment) and looks only at the exit status:
| Exit status | Meaning |
|---|---|
| 0 | healthy: the application works |
| 1 | unhealthy: the application does not work |
| 2 | reserved; do not use it |
From these results, Docker keeps a health status for the container, which is one of three values:
- starting: the container has started and has not yet passed a check.
- healthy: the most recent check succeeded.
- unhealthy: the check has failed a given number of times in a row.
The timing settings control when checks run and how failures are counted:
| Option | Default | Meaning |
|---|---|---|
--interval | 30s | time between checks once the container is running |
--timeout | 30s | a check that runs longer than this counts as a failure |
--start-period | 0s | grace period after start; failures during it do not count |
--start-interval | 5s | time between checks during the start period (Docker Engine 25 and later) |
--retries | 3 | consecutive failures needed to become unhealthy |
The start period exists because many applications need time to initialize: loading configuration, running migrations, warming caches. Failures during that period are ignored, but a single success ends the start period immediately and marks the container healthy. --start-interval lets Docker check often during startup, so that a fast application is reported healthy within a second or two, and less often afterwards.
Defining a Health Check
In the Dockerfile
The usual place for a health check is the image itself, through the HEALTHCHECK instruction, so that every container started from the image is checked the same way. The demo application in this lesson is a small web server written in Bash (the same style as in lesson 175), with an HTTP endpoint and two files that simulate faults: /tmp/hang makes the application deadlock, and /tmp/broken makes every request fail with status 500. Its Dockerfile:
FROM demo/base:1.0
COPY server.sh healthcheck.sh /app/
ENV PORT=8080
HEALTHCHECK --interval=5s --timeout=3s --start-period=10s --start-interval=1s --retries=3 \
CMD ["/app/healthcheck.sh"]
USER app
CMD ["/app/server.sh"]
The intervals are short so that the examples finish quickly; production services typically use intervals of 10 to 30 seconds. The examples were run with Docker Engine 29.9; the base image demo/base:1.0 is a minimal locally built image containing Bash and a few standard tools, but no curl or wget.
HEALTHCHECK has two forms, like CMD. The exec form, CMD ["/app/healthcheck.sh"], runs the program directly. The shell form, CMD /app/healthcheck.sh --quick || exit 1, passes the text to /bin/sh -c; Docker records it as CMD-SHELL. docker inspect shows what the image defines, with durations in nanoseconds:
docker inspect --format '{{json .Config.Healthcheck}}' web | jq -c .
{"Test":["CMD","/app/healthcheck.sh"],"Interval":5000000000,"Timeout":3000000000,"StartPeriod":10000000000,"StartInterval":1000000000,"Retries":3}
On the command line
docker run can add a health check to an image that has none, replace the image's check, or disable it:
docker run -d --name plain2 --health-cmd 'test -d /app' --health-interval 2s demo/base:1.0 sleep 300
docker run -d --name nohc --no-healthcheck demo/webapp:2.0
--health-cmd always uses the shell form, so docker inspect shows ["CMD-SHELL","test -d /app"] for it. The --health-interval, --health-timeout, --health-start-period, --health-start-interval and --health-retries options correspond to the Dockerfile options. Docker Compose files offer the same settings under a service's healthcheck: key.
Writing the Check Command in Bash
A health check should test what users depend on, quickly, and without tools the image may not contain. Minimal images often have neither curl nor wget, but if the image has Bash, its /dev/tcp feature can open a TCP connection without any external program: redirecting to the special path /dev/tcp/HOST/PORT makes Bash connect to that address.
#!/bin/bash
# Health check: request /health and require HTTP status 200.
port=${PORT:-8080}
{ exec 3<> "/dev/tcp/127.0.0.1/$port"; } 2> /dev/null || { echo "cannot connect to port $port"; exit 1; }
printf 'GET /health HTTP/1.0\r\nHost: localhost\r\n\r\n' >&3
IFS= read -r -t 2 status_line <&3 || { echo "no response within 2s"; exit 1; }
status_line=${status_line%$'\r'}
[[ $status_line == "HTTP/1."?" 200 "* ]] || { echo "bad status: $status_line"; exit 1; }
echo "healthy: $status_line"
How the check works:
exec 3<> /dev/tcp/127.0.0.1/$portopens file descriptor 3 for reading and writing, connected to the application's port. If nothing is listening, the redirection fails. Wrapping it in{ ...; } 2> /dev/nullhides Bash's own error message: a redirection written directly onexecwould apply to the rest of the script, while the braces limit it to this one command.printf ... >&3sends a minimal HTTP request. HTTP requires\r\nline endings and an empty line at the end of the headers.read -r -t 2reads the first line of the response, the status line such asHTTP/1.0 200 OK, and gives up after 2 seconds. This internal limit keeps the script below Docker's 3-second--timeout, so a slow application produces a clear message instead of being killed.${status_line%$'\r'}removes the carriage return that ends every HTTP line.- The pattern
"HTTP/1."?" 200 "*accepts HTTP/1.0 and HTTP/1.1 with status 200 and rejects everything else. - Every exit path prints one line. Docker stores the output of each check, so the message explains a failure to whoever investigates it later.
The check deliberately requests /health, an endpoint whose purpose is to report whether the application can serve requests, rather than only testing whether the port is open. An application that accepts connections but answers every request with an error passes a port test but fails this one. A useful health endpoint checks the application's own critical dependencies, such as its database connection, but stays cheap, because it runs every few seconds for as long as the container lives.
Reading the Health State from Scripts
The status
docker inspect exposes the health state under .State.Health. A container started from the image goes from starting to healthy within about a second, thanks to the 1-second start interval:
docker run -d --name web demo/webapp:2.0
for i in 1 2 3 4 5 6; do echo "$(date +%T) $(docker inspect -f '{{.State.Health.Status}}' web)"; sleep 0.7; done
docker ps --format '{{.Names}}\t{{.Status}}'
04:20:37 starting
04:20:38 starting
04:20:39 healthy
04:20:39 healthy
04:20:40 healthy
04:20:41 healthy
web Up 4 seconds (healthy)
For a container without a health check, .State.Health does not exist and the template fails. Scripts that handle any container should test for it with if:
docker run -d --name plain demo/base:1.0 sleep 300
docker inspect -f '{{.State.Health.Status}}' plain; echo "[status $?]"
docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' plain
template parsing error: template: :1:8: executing "" at <.State.Health.Status>: map has no entry for key "Health"
[status 1]
none
The check history
Docker keeps the results of the last five checks in .State.Health.Log, each with its start time, exit code and output (up to the first 4 KB), and counts consecutive failures in .State.Health.FailingStreak. After creating /tmp/broken in the container, the status changes to unhealthy once three checks in a row have failed:
docker exec web touch /tmp/broken
start=$(date +%s)
while [[ $(docker inspect -f '{{.State.Health.Status}}' web) == healthy ]]; do sleep 0.5; done
echo "unhealthy after $(( $(date +%s) - start ))s"
docker inspect --format '{{.State.Health.Status}} {{.State.Health.FailingStreak}}' web
docker inspect web | jq -r '.[0].State.Health.Log[] | "\(.Start[11:19]) exit=\(.ExitCode) \(.Output | rtrimstr("\n"))"'
unhealthy after 18s
unhealthy 3
04:20:43 exit=0 healthy: HTTP/1.0 200 OK
04:20:48 exit=0 healthy: HTTP/1.0 200 OK
04:20:53 exit=1 bad status: HTTP/1.0 500 Internal Server Error
04:20:58 exit=1 bad status: HTTP/1.0 500 Internal Server Error
04:21:04 exit=1 bad status: HTTP/1.0 500 Internal Server Error
The time to detection is roughly interval × retries, here 15 seconds plus the time until the next scheduled check. This is the trade-off in the settings: short intervals and few retries detect failures quickly but may react to a brief hiccup, while long ones are tolerant but slow.
A check that exceeds its timeout is recorded with the exit code -1. Here a check that sleeps 5 seconds runs with a 1-second timeout:
docker run -d --name slow --health-cmd 'sleep 5' --health-timeout 1s --health-interval 2s --health-retries 1 demo/base:1.0 sleep 60
sleep 5
docker inspect slow | jq -c '.[0].State.Health | {Status, FailingStreak, last: .Log[-1] | {ExitCode, Output}}'
{"Status":"unhealthy","FailingStreak":1,"last":{"ExitCode":-1,"Output":"Health check exceeded timeout (1s)"}}
Filtering by health
docker ps --filter health=... selects containers by status; the possible values are starting, healthy, unhealthy and none (no health check):
docker ps --filter health=unhealthy --format '{{.Names}} {{.Status}}'
docker ps --filter health=none --format '{{.Names}}'
web Up 26 seconds (unhealthy)
nohc
plain
Health events
Every change of health status also produces an event. docker events streams events as they happen, which lets a script react without polling:
docker events --filter container=web --filter event=health_status \
--format '{{.Actor.Attributes.name}} {{.Action}}'
web health_status: healthy
web health_status: unhealthy
The command runs until it is interrupted. In the format, .Action contains the event type with the new status; .Actor.Attributes contains the container's name, image and labels.
What Docker Does with an Unhealthy Container
On a single Docker Engine, the answer is: nothing. Health status is information only. Restart policies such as --restart unless-stopped react when the container's main process exits, not when its health check fails. The test container above was started with --restart unless-stopped and stayed unhealthy:
docker inspect -f '{{.State.Status}} {{.State.Health.Status}} restarts={{.RestartCount}}' web
running unhealthy restarts=0
The health status is still used: Docker Swarm replaces unhealthy tasks, Docker Compose can start a service only after another one is healthy (depends_on with condition: service_healthy), and load balancers and monitoring can read it. But on a plain Docker host, acting on unhealthy containers is the job of a script, which is the subject of the rest of this lesson.
Waiting Until Containers Are Healthy
Deployment and test scripts often start several containers and must wait until they are ready before continuing, for example before running database migrations or integration tests. A fixed sleep 10 is either too long or not long enough. The health status gives an exact answer:
# wait_healthy TIMEOUT NAME...: wait until every named container is healthy
wait_healthy() {
local timeout=$1 name state deadline pending
shift
deadline=$(( EPOCHSECONDS + timeout ))
while :; do
pending=()
for name in "$@"; do
state=$(docker container inspect --format \
'{{if .State.Health}}{{.State.Health.Status}}{{else}}no-healthcheck{{end}}' "$name" 2> /dev/null) ||
state=missing
case $state in
healthy) ;;
starting) pending+=("$name") ;;
*) echo "$name: $state" >&2; return 1 ;;
esac
done
(( ${#pending[@]} == 0 )) && return 0
if (( EPOCHSECONDS >= deadline )); then
echo "still starting after ${timeout}s: ${pending[*]}" >&2
return 1
fi
sleep 1
done
}
The function checks every container in each round and collects the ones still starting. It succeeds when none are left, and fails immediately for anything that can never become healthy: an unhealthy container, a missing one, or one without a health check. Otherwise it gives up at the deadline, naming the containers that are still not ready:
docker run -d --name db demo/webapp:2.0
docker run -d --name api demo/webapp:2.0
wait_healthy 30 db api; echo "[status $?]"
wait_healthy 30 db api nosuch; echo "[status $?]"
wait_healthy 30 db plain; echo "[status $?]"
docker run -d --name slowapp --health-cmd 'false' --health-start-period 60s --health-interval 30s demo/base:1.0 sleep 60
wait_healthy 3 db slowapp; echo "[status $?]"
[status 0]
nosuch: missing
[status 1]
plain: no-healthcheck
[status 1]
still starting after 3s: slowapp
[status 1]
slowapp's check always fails, but during its 60-second start period the failures do not count, so it stays in starting and the function stops at its 3-second deadline.
A Complete Example: Restarting Unhealthy Containers
health-watch.sh adds the missing reaction to a single Docker host. It restarts containers that become unhealthy, but only containers that opt in with the label autoheal=true, and only a limited number of times. The limit matters: a restart fixes problems that live in the process's memory, such as a deadlock or a leaked connection pool, but not a problem outside it, such as an unreachable database or a full disk. Restarting such a container every minute would hide the failure and cause additional load; after a few attempts, the script stops and reports that a person is needed.
#!/usr/bin/env bash
#
# health-watch.sh - restart Docker containers that become unhealthy
#
# Watches every container that has the label autoheal=true. When Docker
# reports one as unhealthy, the script logs the last health check output
# and restarts the container. A container that keeps failing is restarted
# at most MAX times within WINDOW seconds; after that it is left alone and
# reported, because restarting it again would only hide a real problem.
#
# Usage: health-watch.sh [-i INTERVAL] [-m MAX] [-w WINDOW] [-1]
# -i INTERVAL seconds between checks (default: 10)
# -m MAX restarts allowed per container within WINDOW (default: 3)
# -w WINDOW length of the restart window in seconds (default: 600)
# -1 check once and exit (for cron or testing)
set -uo pipefail
interval=10 max_restarts=3 window=600 once=0
usage() { echo "usage: ${0##*/} [-i INTERVAL] [-m MAX] [-w WINDOW] [-1]" >&2; exit 2; }
log() { printf '%(%H:%M:%S)T %s\n' -1 "$*"; }
while getopts ':i:m:w:1' opt; do
case $opt in
i|m|w) [[ $OPTARG =~ ^[1-9][0-9]*$ ]] || usage ;;&
i) interval=$OPTARG ;;
m) max_restarts=$OPTARG ;;
w) window=$OPTARG ;;
1) once=1 ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# == 0 )) || usage
# Only one watcher may run at a time (lesson 171)
exec 9> /run/lock/health-watch.lock || exit 2
flock -n 9 || { echo "${0##*/}: already running" >&2; exit 2; }
declare -A history=() # container ID -> recent restart times (epoch seconds)
declare -A gave_up=() # container ID -> 1 once the watcher stopped restarting it
# last_output ID: output of the most recent health check, joined into one line
last_output() {
docker container inspect "$1" 2> /dev/null |
jq -r '.[0].State.Health.Log[-1].Output // "" | gsub("\\s+"; " ") | rtrimstr(" ")'
}
# handle ID NAME: decide what to do with one unhealthy container
handle() {
local id=$1 name=$2 now=$EPOCHSECONDS t recent=()
[[ -n ${gave_up[$id]:-} ]] && return 0
# keep only the restarts that happened inside the window
for t in ${history[$id]:-}; do
(( now - t < window )) && recent+=("$t")
done
if (( ${#recent[@]} >= max_restarts )); then
gave_up[$id]=1
log "GIVING UP on $name: unhealthy again after ${#recent[@]} restarts in ${window}s; needs a human"
return 1
fi
log "$name is unhealthy: $(last_output "$id")"
if docker restart --time 10 "$id" > /dev/null; then
recent+=("$now")
log "$name restarted (restart ${#recent[@]} of $max_restarts allowed in ${window}s)"
else
log "could not restart $name"
fi
history[$id]=${recent[*]}
}
check_once() {
local id name status=0
# forget containers that are healthy again, so a later failure starts fresh
for id in "${!gave_up[@]}"; do
[[ $(docker container inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$id" 2> /dev/null) == unhealthy ]] ||
unset 'gave_up[$id]'
done
while IFS=$'\t' read -r id name; do
handle "$id" "$name" || status=1
done < <(docker ps --filter label=autoheal=true --filter health=unhealthy --format '{{.ID}}\t{{.Names}}')
return "$status"
}
if (( once )); then
check_once
exit
fi
trap 'log "watcher stopping"; exit 0' INT TERM
log "watching containers labelled autoheal=true every ${interval}s (max $max_restarts restarts per ${window}s)"
while :; do
check_once
sleep "$interval" & wait $!
done
How It Works
- Opt-in by label.
docker ps --filter label=autoheal=true --filter health=unhealthylists exactly the containers the watcher is responsible for and that need attention now. Both filters must match. Containers without the label are never touched, so a database that must not be restarted automatically simply does not get the label. - Option validation. The
;;&terminator in thecasestatement makes Bash continue testing the following patterns after a match. The first pattern validates the argument of-i,-mand-was a positive integer, and the next pattern stores it. Rejecting0prevents an interval of zero, which would turn the loop into a busy loop that queries Docker continuously. - Restart history per container. The associative array
history(lesson 102) maps each container ID to the times of its recent restarts, stored as a space-separated string because Bash arrays cannot be nested. Before each restart,handlekeeps only the times inside the window. IfMAXrestarts already happened within the window, the container has failed again despite them, and the script gives up. IDs are used instead of names because a name can be reused by a different container. - Giving up is remembered.
gave_upprevents the "giving up" message from being repeated every interval. At the start of each round, containers ingave_upthat are no longer unhealthy are removed from it, so a container fixed by an administrator is watched normally again. - The reason is logged.
last_outputtakes the last entry of the health log withjqand joins its lines withgsub, so the log records why the container was considered unhealthy at the moment of the restart. After the restart, that information is still in Docker's health log, but it is soon pushed out by new entries. docker restart --time 10sendsSIGTERM, waits up to 10 seconds for the application to exit, then sendsSIGKILLand starts the container again with the same configuration. A restart done this way does not increase.RestartCount, which counts only restarts made by the restart policy.- Exit status.
check_oncereturns 1 when it gave up on at least one container. In-1mode this becomes the script's exit status, so cron or a monitoring system can alert on it (lesson 173). - Polling instead of events. The watcher checks every few seconds instead of following
docker events. Polling is simpler and self-correcting: if Docker restarts or the watcher misses an event, the next round still sees every unhealthy container. With health checks every few seconds, a polling interval of 10 seconds adds little delay. - Interruptible sleep and a lock.
sleep "$interval" & wait $!lets theTERMtrap run immediately when the watcher is stopped (lesson 141), andflockmakes sure only one watcher runs (lesson 171).
Running the Complete Example
Three containers were started from the demo image: shop and billing with the label, reports without it, all with --restart unless-stopped:
docker run -d --name shop --label autoheal=true --restart unless-stopped demo/webapp:2.0
docker run -d --name billing --label autoheal=true --restart unless-stopped demo/webapp:2.0
docker run -d --name reports --restart unless-stopped demo/webapp:2.0
The watcher was started in the background with a 3-second interval and a limit of 2 restarts per 5 minutes. Then three faults were injected: shop deadlocks, which a restart fixes; billing returns errors because of a fault that survives a restart (the /tmp/broken file lives in the container's filesystem, which a restart keeps); and reports gets the same fault but has no label:
health-watch.sh -i 3 -m 2 -w 300 > watch.log 2>&1 &
docker exec shop touch /tmp/hang
docker exec billing touch /tmp/broken
docker exec reports touch /tmp/broken
Starting a second watcher, or giving an invalid option, fails with status 2:
$ health-watch.sh -1
health-watch.sh: already running
[status 2]
$ health-watch.sh -i 0
usage: health-watch.sh [-i INTERVAL] [-m MAX] [-w WINDOW] [-1]
[status 2]
About 90 seconds later, the watcher's log and the container list showed the outcome:
04:25:34 watching containers labelled autoheal=true every 3s (max 2 restarts per 300s)
04:25:52 billing is unhealthy: bad status: HTTP/1.0 500 Internal Server Error
04:25:53 billing restarted (restart 1 of 2 allowed in 300s)
04:25:53 shop is unhealthy: cannot connect to port 8080
04:25:53 shop restarted (restart 1 of 2 allowed in 300s)
04:26:14 billing is unhealthy: bad status: HTTP/1.0 500 Internal Server Error
04:26:14 billing restarted (restart 2 of 2 allowed in 300s)
04:26:35 GIVING UP on billing: unhealthy again after 2 restarts in 300s; needs a human
reports Up About a minute (unhealthy)
billing Up 48 seconds (unhealthy)
shop Up About a minute (healthy)
Each container ended in the expected state:
shop had stopped accepting connections. One restart repaired it, and it has been healthy since. Its own log shows the sequence: the deadlock, the stop requested by
docker restart, and the fresh start.webapp listening on port 8080 webapp: deadlocked webapp: stopping webapp listening on port 8080billing became unhealthy again after each restart, about 20 seconds later (the 1-second start interval finds the error immediately, but failures during the 10-second start period do not count, and three more failures are needed afterwards). After the second restart, the watcher stopped and reported it, as intended: its fault is outside the process.
reports has the same fault but no
autoheallabel, so the watcher left it alone. Its restart policy did not restart it either, because its process never exited.
To run the watcher permanently, start it as a systemd service, or run health-watch.sh -1 from cron every minute (lesson 170). In cron mode, the restart history is lost between runs, because every run is a new process; a version for cron would store the history in a file, for example under /var/lib/health-watch/.