Open In App

What is Docker Health Check ?

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Docker Healthcheck instruction facilitates maintaining optimal docker container performance. It watchfully makes your container well-maintained by letting them know the status of the container. This article demonstrates the health check usage and its significance through a practical go-through using a Nginx container in the docker environment.

What Is HEALTHCHECK Instruction In Docker?

The HEATHCHECK instruction is a feature in Docker that determines the state of a Docker Container. It determines whether the Container is running in a normal state or not. It performs health checks at regular intervals. The initial state is starting and after a successful checkup, the state becomes healthy. If the test remains unsuccessful, it turns into an unhealthy state. 

Docker HealthCheck

Docker Healthcheck is an instruction that comes with 2 forms of commands. Those syntaxes are specified below. Mainly this instruction is used as a command to know the status of the container and verify whether it is still working or not. The status of the container’s health becomes healthy to unhealthy after certain number of failures.

Syntax:

HEALTHCHECK   [ OPTIONS ]   CMD  command 

( or )

Syntax:

HEALTHCHCK NONE

Health Check Configurations

  • Some options provided by the HEALTHCHECK instruction are as follows:

Options

Functionality

–interval

It determines the interval between 2 health check-ups. The default interval is the 30s.

–timeout

If the HEALTHCHECK command exceeds the specified duration, it is categorized as a failure. The default duration is the 30s.

–retries

If it reaches the specified number of retries, the state is considered to be unhealthy. The default number of retries is 3.

–start-period

It heps in defining the delay period before the first retry attempt. By default it will be started immediately.

–start-interval

It helps in determining the interval between the first and second retry. By default the interval will be 4 seconds.

Docker Healthcheck Examples

Docker Health check instructions are defined inside the Dockerfile or in Docker-Compose files. For bettering here we defining a sample healthcheck in a Dockerfile, for a docker container that running a web server.

  • Here, The health check instruction runs for every 30seconds of intervals ( –interval=30s ) , With a timeout of 10seconds ( –timeout=10s ) and retries of 3 times. It will check the reachability of the NGINX server using `curl` option, if the it fails ( i.e., unreachability ) then it will exits with status of 1.
 FROM nginx:latest

# Define a healthcheck command
HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD curl -f http://localhost/ || exit 1

How to Write a Custom Health Check Scripts

For writing a custom health check, you can go for shell scripting in that you can write the code for performing necessary checks and returns. If status is healthy then exit value is 0 or if status is unhealthy then the exit value is non-zero. Here is an example using a shell script.

  • Save this healthcheck code with filename as “healthcheck.sh” and provide the executable permissions such as `chmod +x healthcheck.sh`
#!/bin/bash

# Check if a service is running
if pgrep "myservice" > /dev/null
then
exit 0 # Service is running, healthcheck passes
else
exit 1 # Service is not running, healthcheck fails
fi

Writing a Custom Health Check in Nodejs

  • We can a custom health checks in Nodejs by creating a simple Node.js script. Here’s an example for this:
// healthcheck.js
const http = require('http');

const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('Healthcheck OK');
});

server.listen(3000, () => {
console.log('Healthcheck server running on port 3000');
});
  • This above script will helps in creating a basic HTTP server that listens on port number 3000. When it is accessed it return a successful status code as 200 and with the message “Health Check OK
  • For Running this script, use the following command before that ensure that node js software is successfully installed in your system.
node healthcheck.js
  • Now, you can perform the Health checks in Dockerfile for this Nodejs application. The following is custom health check scripted Dockerfile.
FROM node:latest

COPY healthcheck.js /app/healthcheck.js

# Define a custom healthcheck command
HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD ["node", "/app/healthcheck.js"]

After running a container with this Dockerfile, the node js application keeps on running for every 30 seconds with a timeout of 10 seconds and retrives of 3.

Common Usages For Docker Health Checks

Let’s start with discussing the docker health check instruction usage in the docker environment before diving into the practical exposure, The following are a few wider uses of the health check instruction.

Evaluating The Health Of The Container

  • Healthcheck evaluates a running container’s health and determines its functionality whether is in normal or unhealthy condition. It performs the automated health check at definite intervals allowing the developer to identify the issues actively.

Periodical Healthcheck

  • It facilitates the automated health checks at defined intervals letting the docker actively identify the issues with continuous monitoring and quick issue resolution.

Customizable Parameters

  • Users can check the health of the containers using options like `–interval`, `–timeout` and `–retrieves` making them suitable for the specific needs of the application facilitating with suitable response thresholds.

Enhanced Troubleshooting

  • The health check not only supports maintaining the application’s reliability but also facilitates defined troubleshooting. Inspecting the status of the container states over multiple checkups supports in effective problem resolution.

Application Crashes

Health checks facilitates with monitoring the application’s status within the container. If in anycase, the application get crashed or it becomes unresponsive then the health check will detects the state and alerts of the docker daemon.

Depedency Failures

Mostly applications will depend on the external things like databases or APIs. Health checks help with verifying the availability and responsiveness of those dependencies. If any dependency looks in failed state or in unreachable then the health check mark it as unhealthy and facilitates Docker in triggering the right measures such as relocating or restarting the container.

Resource Limitations

Health checks facilitating in monitoring the utilization of the resources usage within the containers such as CPU and memory utilization. Health check reports this unhealthy state to the Docker and Docker will takes measures in redistributing the resources or restarting the containers on different hosts.

Misconfigurations

Invalid, Incorrect configurations of applications leads to instability and failure of the applications. It verifies the essential configuration parameters such as network connectivity settings or environment variables. Health check look over the application status if any misconfiguration are detected then it is prompted to Docker to stop those containers and provides the feedback for troubleshooting.

Now let’s see with practical examples of how to use the HEALTHCHECK Instruction in your Dockerfile. We will create an Nginx Container and determine it states.

How To Use And Run Docker’s Health Check Command: A Step-By-Step Guide

The following are the step-by-step guidelines for the implementation of the health check in docker using Nginx Image:

Step 1: Create A Dockerfile

  • You can use the following template code to create the Dockerfile.
  • In the Dockerfile, we pull the nginx base image and perform a healthcheck with the specified interval and timeout. 
FROM nginx:latest
HEALTHCHECK --interval=35s --timeout=4s CMD curl -f https://localhost/ || exit 1
EXPOSE 80

Step 2: Build The Docker Image

  • We can build the Docker Image using the build command as follows:
sudo docker build -t healthcheck-demo .

building the image

Step 3: Run the Container

  • Here, we will check whether the nginx.conf file exists or not. We will set the Command while running the Docker Container.
sudo docker run --name=healthcheck-demo -d
--health-cmd='stat /etc/nginx/nginx.conf
|| exit 1' healthcheck-demo

/* This line must be without the breaks, it's done for viewing purpose*/

running the container

Step 4: Determine the state of the Container

  • You can use the inspect command to determine the state of the Container.
sudo docker inspect --format=' ' healthcheck-demo
  • You will get all the details regarding the Container along with the states during all the health checkups.

state of containerhealth of the container

Docker HealthCheck Commands

  • On using the `docker inspect` command we can check the status of a container:
docker inspect --format='{{json .State.ExitCode}}' <container_name>
  • The below screenshot, we have container with name “mycontainer” in running state.

  • Now, the below screenshot illustrates about the healthcheck of above specified container “mycontainer” with above specified command:
docker inspect --format='{{json .State.ExitCode}}' mycontainer

Docker HealthCheck Docker-Compose

  • We can define the health checks in Docker-Compose yaml file under a service as follows:
services:
myservice:
image: myimage
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s

Docker HealthCheck curl

  • We can use the curl command inside the Dockerfile for performing the HealthChecks.
HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD curl -f http://localhost || exit 1

Docker health Check Logs

  • We can view the Docker health check logs with the following command:
docker inspect --format='{{json .State.Health}}' <container_name>
  • Here, we are taking running container with name mycontainer as example, now the command looks as follows:
docker inspect --format='{{json .State.Health}}' mycontainer

Docker Health Check Ports

  • On using the following command we can see the exposed ports and its respective mapping:
docker ps
docker port <container_name>

Docker Health Check Scripts

  • On creating the custom healthcheck scripts and including them in your Dockerfile.
HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD ["./healthcheck.sh"]

Docker Health Check Status

  • On using the following command you can check the status of a container.
docker inspect --format='{{json .State.Health.Status}}' <container_name>

Conclusion

To conclude, in this article we discussed what is HEALTHCHECK instructions, what are its uses, the various options you can use along with it. We used the nginx container to demonstrate the same with practical examples. It’s usage is crucial for monitoring and maintaining the health of containerized applications. Implementation of health checks with Docker applications will be an effective practice for ensuring reliability and stability to the containerized applications.

Docker HealthCheck Instruction – FAQ’s

What Is The Healthcheck In Docker?

It refers to the HEALTHCHECK instruction, a feature allowing the definition of periodic checks to knows the status of container’s health.

What is Health Check In Dockerfile or Docker Compose?

Healthcheck is an instructions that check status of the application whether it is reachable or unreachable, properly working or being instable. It is defined as command in Dockerfile or DockerCompose to check the health of the containerized applications ensuring its reliability and availability.

What is the cURL command for Docker Health check?

The commonly used curl command for Docker health checks is curl -f <URL>`. It checks if the specified URL is reachable ( successful ) or it coming with non-zero exit status code known as failure state.

How Do I Disable Healthcheck In Docker?

You can disable the docker healthcheck, on onmiting the healthcheck instruction in the Dockerfile or by using `–no-healthcheck` during the `docker run` command.

How To Check The Container Status In Docker?

On using docker inspect command particularly with the –format=’ ‘ you can retrieve the detailed information, including the container’s health status.

Does Kubernetes Use Docker Healthcheck Instruction?

Yes, Kubernetes use the docker healthcheck as part of its container orchestration facilitating health status of containers.

How Does The Docker Compose Healthcheck Work?

In Docker compose the healthchecks are defined in the service’s configuration of the compose file specifying the test commands and options.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads