Docker – HEALTHCHECK Instruction
A HEATHCHECK instruction 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.
Some options provided by the HEALTHCHECK instruction are –
- –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.
In this article, we will see practical examples of how to use the HEALTHCHECK command in your Dockerfile. We will create an Nginx Container and determine it states. Follow the below steps to Check the health of your dockerfile:
Step 1: Create a Dockerfile
You can use the following template to create the Dockerfile.
FROM nginx:latest HEALTHCHECK --interval=35s --timeout=4s CMD curl -f https://localhost/ || exit 1 EXPOSE 80
In the above Dockerfile, we pull the nginx base image and perform a HEALTHCHECK with the specified interval and timeout.
Step 2: Build the Docker Image
We can build the Docker Image using the build command.
sudo docker build -t healthcheck-demo .
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*/
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.
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.