Module 6 Lesson 4: Docker Healthchecks
·DevOps

Module 6 Lesson 4: Docker Healthchecks

Is your app actually alive? Learn how to define HEALTHCHECK instructions in your Dockerfile so your orchestrator can detect and fix 'Zombie' containers.

Module 6 Lesson 4: Docker Healthchecks

A container status can be "Running," but the app inside might be frozen, crashed, or stuck in an infinite loop. This is a "Zombie Container."

The HEALTHCHECK instruction allows Docker to "Ping" the app inside to see if it's actually working.

1. The Syntax

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

Options:

  • --interval: How often to run the check (default: 30s).
  • --timeout: How long to wait for the check to finish (default: 30s).
  • --retries: How many failures before the container is marked "Unhealthy" (default: 3).
  • --start-period: Give the app time to "Warm up" before starting checks.

2. Viewing Health Status

When you run docker ps, you will now see an extra status indicator:

  • Up 5 minutes (health: starting)
  • Up 5 minutes (healthy)
  • Up 5 minutes (unhealthy)

3. Why Healthchecks Matter

  1. Orchestration: If a container becomes unhealthy, tools like Docker Swarm or Kubernetes can automatically Restart it or stop sending traffic to it.
  2. Zero-Downtime Deploys: Compose can wait until the new version is "healthy" before shutting down the old version.
  3. Self-Healing: It removes the need for manual monitoring of internal app state.

4. Healthcheck in Docker Compose

You can also define healthchecks in your docker-compose.yml file, which is often easier to manage than hardcoding them into the image.

services:
  web:
    image: my-app
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost"]
      interval: 1m30s
      timeout: 10s
      retries: 3
      start_period: 40s

Exercise: The Liveness Test

  1. Find an image that has curl or wget installed (e.g., nginx:alpine).
  2. Write a Dockerfile that adds a HEALTHCHECK that tries to download the index page every 5 seconds.
  3. Build and run it. Watch docker ps.
  4. The Crash: Use docker exec to "Delete" the index file: rm /usr/share/nginx/html/index.html.
  5. Watch docker ps. How long does it take for the status to change to unhealthy?
  6. Bonus: How can you tell Docker Compose to "Restart" the container automatically when it becomes unhealthy? (Research: restart_policy).

Summary

Healthchecks move your infrastructure from "Stateless" to "Self-Aware." By teaching Docker how to tell if your app is sick, you reduce your "On-call" stress and ensure your users always hit a working server.

Next Lesson: Entrypoint vs. Command: The runtime instructions.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn