BudiBadu Logo
Samplebadu

Dockerfile by Example: Healthcheck Instruction Schema

Docker Engine 20.10+

Docker can periodically check if your application is working correctly. This sample code demonstrates how to use HEALTHCHECK to define a custom probe command.

Code

FROM nginx:alpine

# Install curl for the healthcheck
RUN apk add --no-cache curl

# Define the healthcheck
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost/ || exit 1

# Options:
# --interval: Time between checks (default: 30s)
# --timeout: Time to wait for check to complete (default: 30s)
# --start-period: Initialization time before failures count (default: 0s)
# --retries: Consecutive failures needed to report unhealthy (default: 3)

Explanation

The HEALTHCHECK instruction defines a command that Docker executes periodically to determine the container's health status. This goes beyond simple process monitoring; it verifies that the application is actually responsive and functioning. A container with a passing health check is marked as healthy, while repeated failures mark it as unhealthy, allowing orchestrators like Docker Swarm to restart it.

Healthcheck configuration options:

  • --interval: Frequency of the check (default 30s)
  • --timeout: Max time for check to complete (default 30s)
  • --start-period: Grace period for startup before failures count
  • --retries: Consecutive failures required to mark unhealthy

The command specified in CMD should return exit code 0 for success and 1 for failure. Using tools like curl -f is common because it returns a non-zero exit code on HTTP errors (like 404 or 500). The --start-period is particularly useful for applications with slow startup times, preventing them from being killed prematurely before they have fully initialized.

Code Breakdown

4
apk add curl installs the tool needed for the check.
7
HEALTHCHECK ... configures the timing parameters.
8
CMD curl -f ... || exit 1 ensures non-zero exit code on failure.
7
--start-period=5s prevents false positives during startup.