Container health checks
- Version
- 29
- Review
- Draft
Summary#
A health check runs a command inside a container and records starting, healthy or unhealthy next to the process state. Exit status 0 passes and 1 fails. Define it with HEALTHCHECK in a Dockerfile or with docker run options.
Syntax#
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD wget -q --spider http://127.0.0.1:8080/ || exit 1
docker run --health-cmd 'test -f /tmp/ready' --health-interval 1s --health-retries 1 IMAGE
Example#
The example uses a local alpine:3 image.
(
set -eu
name="dlr-docker-commands-health-$$"
trap 'docker rm -f "$name" >/dev/null 2>&1 || true' EXIT
docker run --pull never --detach --name "$name" \
--health-cmd 'test -f /tmp/ready' --health-interval 1s --health-retries 1 \
alpine:3 sleep 60 >/dev/null
wait_for() {
tries=0
until [ "$(docker inspect --format '{{.State.Health.Status}}' "$name")" = "$1" ]; do
tries=$((tries + 1))
[ "$tries" -lt 30 ]
sleep 1
done
docker inspect --format '{{.State.Status}} {{.State.Health.Status}}' "$name"
}
wait_for unhealthy
docker exec "$name" touch /tmp/ready
wait_for healthy
)
Expected output#
running unhealthy
running healthy
Common mistakes#
The check runs inside the container, so its program must exist in the image and 127.0.0.1 refers to the container itself. A container can keep running while unhealthy, as the first output line shows. Docker Engine restart policies do not react to health changes alone.
Version applicability#
Checked with Docker Engine 29. The start interval option, --start-interval in a Dockerfile, requires Docker Engine 25.0 or later. Only the last HEALTHCHECK instruction in a Dockerfile takes effect.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0