Course contentsShow
← Cloud and Infrastructure
Lesson 1013 of 2,98920. Docker in DepthFree lesson

HEALTHCHECK: Container Health

Understand HEALTHCHECK instruction for defining container health probes, intervals, and failure thresholds.

What You'll Learn

You'll learn how to use Docker's HEALTHCHECK instruction to automatically monitor whether your containerized application is actually working, not just running.

Why HEALTHCHECK Matters

A container process can be running without the application inside being healthy. Your web server might be up, but stuck in a deadlock or unable to accept connections. HEALTHCHECK lets Docker periodically test if your container is actually functioning, not just whether the process exists.

Think of it like a smoke detector: the building might still be standing, but you need an active sensor to know if something's wrong inside.

How HEALTHCHECK Works

Add a HEALTHCHECK instruction in your Dockerfile to define a command Docker should run to verify health:

FROM nginx:alpine
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD curl -f http://localhost/ || exit 1

Parameters:

  • --interval: Time between checks (default: 30s)
  • --timeout: Max time for check to complete (default: 30s)
  • --retries: Consecutive failures before marking unhealthy (default: 3)
  • --start-period: Grace time before health checks count (default: 0s)

The command must exit 0 for healthy, or 1 for unhealthy.

Practical Example

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
HEALTHCHECK --interval=15s --timeout=5s --start-period=10s --retries=2 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD ["node", "server.js"]

Docker now checks /health every 15 seconds. After 2 failed checks, the container shows as "unhealthy" — orchestrators can restart it automatically.

Key Takeaway:
HEALTHCHECK transforms containers from "process exists" to "application works," enabling automatic recovery and reliable deployments by defining health probes with intervals and failure thresholds.