Dockerfile is referred to as an instructions file that contains the essential instructions to dockerize or containerizes the application or a program. The Dockerfile allows us to implement the health check in a container to check the container’s health. The Health check is a process of checking the health of a running container to ensure that the program will execute normally inside the container. The health check helps indicate unusual situations like container resources are not working, or processes within the container are executing.
This tutorial will demonstrate the method for implementing the Docker healthcheck in Dockerfile.
How to Implement Healthcheck in Dockerfile?
The Dockerfile configures the application or program inside the container to containerize it. To implement the healthcheck along with other configurations to check the container’s health, utilize the listed steps.
Step 1: Make Dockerfile
First, create a file named “Dockerfile” and add instructions to Dockerize the project. For instance, we have dockerized the “index.html” program. In Dockerfile, also implement the healthcheck for the container using the following configurations:
-
- “FROM” instruction defines the base image to dockerize the program.
- “COPY” is used to copy the source files to the container’s path.
- “HEALTHCHECK” instruction is used to implement a health check on the container. Here, this instruction utilizes the “–interval” and “–timeout” options.
- “–interval” specifies the time duration in which the health check process will execute.
- “–timeout” option allocates the time duration to wait for a healthcheck.
- “CMD” is used to test the container. Here, we use the “curl” command to get the response from the specified domain.
- “EXPOSE” is utilized to allocate the exposing port:
COPY index.html /usr/share/nginx/html/index.html
HEALTHCHECK --interval=30s --timeout=3s \
CMD curl -f http://localhost/ || exit 1
EXPOSE 80
Step 2: Generate the Docker Image
After that, build the image from the instructions specified in Dockerfile through the given command:
Step 3: Run Container
Next, run the image to run the container and to implement the healthcheck on it:
Here:
-
- “–name” is utilized to define the container’s name.
- “-p” assigns the exposing port for the container:
Step 4: Check Container Health Status
After that, check the health condition by listing the Docker containers:
From the output, you can see that our container is in a healthy state:
Navigate to the port to check if our application is running on the container’s exposed port:
That’s all about implementing healthcheck in Dockerfile.
Conclusion
To implement the healthcheck in Dockerfile, first, create a Dockerfile and configure the instructions to containerize the application. Also, utilize the “HEALTHCHECK” instruction along with “–interval” and “–timeout” options to implement the healthcheck through Dockerfile. This write-up has demonstrated how to implement the healthcheck in Dockerfile.