4.2.13.1 HEALTHCHECK Container Command
A focused guide to HEALTHCHECK Container Command, connecting core concepts with practical Docker and container operations.
The HEALTHCHECK container command is the specific command Docker executes, on a recurring schedule, inside a running container to determine its current health status, with the command's exit code being the sole basis for that determination.
Writing an Effective Health Check Command
A good health check command should be lightweight, fast, and genuinely indicative of whether the application is functioning, rather than merely confirming the process exists.
HEALTHCHECK CMD curl -f http://localhost:8080/health || exit 1
Hitting a dedicated health endpoint that the application itself exposes, and that performs at least a basic internal check (such as confirming a database connection is alive), provides a meaningful signal beyond simply "the process is running."
Checking a TCP Port Without HTTP
For applications that do not expose an HTTP health endpoint, a simpler check can confirm a specific port is accepting connections.
HEALTHCHECK CMD nc -z localhost 5432 || exit 1
Writing a Custom Health Check Script
For more complex health logic, a dedicated script can be copied into the image and used as the health check command, allowing arbitrarily sophisticated checks beyond what a single inline command conveniently expresses.
COPY healthcheck.sh /healthcheck.sh
HEALTHCHECK CMD /healthcheck.sh
#!/bin/sh
curl -sf http://localhost:8080/health | grep -q '"status":"ok"' || exit 1
Exit Code Conventions
The health check command's exit code, and only its exit code, determines whether Docker considers the container healthy — 0 means healthy, any non-zero value means unhealthy, exactly mirroring standard Unix command conventions.
echo $?
Checking this immediately after manually running the health check command confirms exactly what exit code it produces under current conditions.
Why the Specific Command Matters
The quality and accuracy of the health check command directly determines how useful the resulting health status actually is — a poorly designed check that always reports healthy, or one that frequently produces false negatives, undermines the entire purpose of having a health check at all.