0
0
DockerConceptBeginner · 3 min read

What is HEALTHCHECK in Dockerfile: Explanation and Example

The HEALTHCHECK instruction in a Dockerfile tells Docker how to test if a container is working properly. It runs a command inside the container at set intervals and reports if the container is healthy or not.
⚙️

How It Works

Think of HEALTHCHECK as a doctor checking on a patient regularly. Docker runs a small test command inside the container every few seconds or minutes to see if the container is still healthy and working as expected. If the test command succeeds, Docker marks the container as healthy; if it fails, Docker marks it as unhealthy.

This helps you know if your app inside the container is running fine or if it needs attention. For example, if a web server inside the container stops responding, the health check will fail, and Docker can alert you or restart the container automatically.

💻

Example

This example shows a Dockerfile with a HEALTHCHECK that tests if a web server inside the container responds on port 80.

dockerfile
FROM nginx:1.23

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

CMD ["nginx", "-g", "daemon off;"]
Output
When running this container, Docker will run the curl command every 30 seconds to check if the web server responds. If it fails 3 times in a row, Docker marks the container as unhealthy.
🎯

When to Use

Use HEALTHCHECK when you want to monitor if your containerized app is working correctly beyond just running. It is useful for:

  • Automatically restarting containers that become unhealthy.
  • Alerting you when a service inside a container stops responding.
  • Improving reliability in production by detecting failures early.

For example, if you run a database or web server in a container, a health check can verify the service is responsive and ready to serve requests.

Key Points

  • HEALTHCHECK runs a command inside the container to test its health.
  • You can set how often and how many times to retry the check.
  • Docker marks containers as healthy or unhealthy based on the check result.
  • Health status helps with automatic recovery and monitoring.

Key Takeaways

HEALTHCHECK tells Docker how to test if a container is working properly.
It runs a command inside the container at regular intervals to check health.
Use HEALTHCHECK to detect failures and improve container reliability.
Docker marks containers healthy or unhealthy based on the check results.
You can customize the check command, interval, timeout, and retries.