In this lesson, you will learn how to use the HEALTHCHECK instruction to ensure Docker automatically monitors your container’s internal health.
Why do we need Health Checks?
When you start a container, Docker checks if the process is running, but it doesn't know if your application is actually working. A web server might be running but stuck in a loop, or a database might be "up" but failing to respond to queries. Without a health check, Docker assumes everything is fine as long as the process is alive.
The HEALTHCHECK instruction tells Docker exactly how to test your app. Docker will periodically execute a command inside your container; if that command fails, Docker marks the container as unhealthy.
Implementing the Health Check
You add the HEALTHCHECK instruction to your Dockerfile. It typically uses a command like curl or wget to ping an endpoint or check a status file.
Here is an example for a simple web server:
FROM nginx:alpine
# Test every 30 seconds, timeout after 3 seconds
HEALTHCHECK --interval=30s --timeout=3s \
CMD curl -f http://localhost/ || exit 1
How it works
--interval=30s: Docker runs this command every 30 seconds.--timeout=3s: If the command takes longer than 3 seconds, Docker considers the check a failure.CMD: This is the instruction. If the exit code is0, the container is healthy. If the exit code is1, it is unhealthy.
Once you build and run this image, you can use docker ps to see the status. Instead of just seeing "Up", you will see "Up (healthy)" or "Up (unhealthy)". This visibility is crucial for reliability, as it allows orchestration tools to detect failing containers and automatically restart them before users notice a service outage.
Key Takeaway: The HEALTHCHECK instruction provides a self-diagnostic mechanism that allows Docker to identify and report the actual operational status of your application, rather than just the status of the process.