Health Check Command in Docker

Development is more reliable and streamlined with Docker container. With Docker container, developers can design fast, easy, and portable applications - both on desktops and in the cloud - by terminating redundant, mundane configuration tasks.

Furthermore, to UIs, CLIs, APIs, and security, Docker's health check integrated end-to-end platform is built to incorporate across the entire application delivery pipeline.

In Docker Containers, the HEALTH CHECK instruction determines their health status. Containers are evaluated in terms of whether they are running normally. In order to maintain its health, it conducts regular checks.

Table Of Contents

  1. What is a health check?
  2. Parameters for health check
  3. Executing a health check
  4. Using Nginx as a sample
  5. Different ways to use Docker health check command
  6. How to proceed if CURL/WGET does not work?

What is a health check?

Dockerfile health checks are used by Docker to confine the health of containers in use. A crucial part of a Docker file health check is determining whether a resource is adequately healthy.

As soon as a consolidated Dockerfile health checks or checkups is completed, the state is considered healthy. In the event that the test is unsuccessful, it becomes an unhealthy state. in the event that the test is not successful, it deteriorates into an unhealthy state.

A health check can be defined in two ways when working with Docker:

  • Dockerfile
  • Docker-compose file.

Set up a health check

The HEALTHCHECK command is employed in the Dockerfile health checks to configure the health check in a Docker container.

In Docker containers, the HEALTHCHECK can be configured in two distinct formats. They are:

HEALTHCHECK [OPTIONS] CMD command

To check the status of the application in the container, the assigned command will be invoked. To initiate a docker health check, we will use curl. This tool pings the server and returns a response. Alternatively, you might consider:

HEALTHCHECK NONE

Parameters for health check

There are four different options available with the HEALTHCHECK command:

  • -interval=DURATION (30s by default)
  • -timeout=DURATION (30s by default)
  • -start-period=DURATION (0s by default).
  • retries should be set to N (default: 3)

A docker health check should be executed within an interval of seconds defined by the interval option. Additionally, the frequency of recurrent health checks will be determined.

The timeout option controls the amount of time Docker health checks waits for an exit code to be returned before deeming your health check failed ( therefore deeming your container unhealthy).

Parameters for health checks

You can specify the start-period option to determine how long your container needs to bootstrap. The container will not be supposed unhealthy if the Docker health check's exit code is greater than zero; however, it will be deemed healthy if the exit code is 0.

The number of simultaneous failures at the docker health check that must arise before a container is labelled unhealthy is confined by the retries option.

Executing a health check

A docker health check indicates the accessibility of a container's workload. Docker containers are not running, regardless of whether they are running.

Despite the fact that your Docker container is still running, your API server won't be able to handle requests if your database goes down. During troubleshooting, this leads to inconvenient experiences.

Executing a health check

It would be possible to verify the availability of the docker container with a simple docker ps. When you add a docker health check, the output of docker ps also encloses the actual container state.

Dockerfiles are configured to perform docker container health check. This command is invoked 30 seconds after it is obtained by the Docker daemon. Using the command's exit code, Docker health check determines whether your container is healthy:

0 – A healthy and functioning container.

1 – Containers are unhealthy, and workloads may not be working.

2 – Docker reserves this status code and it should not be utilized.

A container's healthiness is displayed in the STATUS column during a Docker ps when HEALTHCHECK is used in the Dockerfile.

As soon as a docker container is created, its health is not checked immediately. As long as the first check has not yet run, the status will show as starting.

During this time, the docker container can perform any startup tasks it needs to. When a container passes a docker health check, it will appear healthy; when it fails, it will consider unhealthy.

Using Nginx as a sample

Here's an instance of how a docker health check performs with the Nginx web service. The subsequent three files are mandated to design a very basic website:

  • An index.html:
// index.html

<html>
    <head>
        <title> Welcome </title>
    </head>
    <body>
        <div style="text-align: center; margin-top: 80px;">
            <h2> Docker Health Check </h2>
            <p> A docker health check is a command used to test the health of a container. Health checks help ensure that a container is running as expected and can be used to prevent or diagnose problems.
            </p>
        </div>
    </body>
</html>
  • A Dockerfile:
FROM nginx
COPY index.html /usr/share/nginx/html/index.html
  • A docker-compose.yml:
version: '3.4'
services:
  web:
    image: very-simple-web
    build:
      context: ./
      dockerfile: Dockerfile
    ports:
      - "127.0.0.1:8000:80"
    restart: unless-stopped

The service will now be created as follows:

docker-compose up -d --build

You can view the output by navigating to localhost:8000.

Different ways to use Docker health check command

HEALTHCHECK instruction in Dockerfiles can have multiple instances, but only the last one takes effect.

Several techniques exist when it comes to creating health checks in Docker. Docker provides the following ways for specifying health checks.

  • Incorporate directly into Dockerfiles
  • Include in the Docker Compose file

Incorporate directly into Dockerfile

Now, we can integrate a health check using the command HEALTHCHECK in the dockerfile directly to check how our container is performing.

Healthcheck Code:

FROM nginx
COPY index.html /usr/share/nginx/html/index.html
HEALTHCHECK CMD curl --fail http://localhost:80

Since the health check command requires the internal port number and not the external port, we have included the internal port number in the URL.

Using the Dockerfile that we have integrated with the health check, let's build and run the Docker image using the following commands:

docker build -t healthcheckdemo .
Docker HealthCheck

Start the container by running the following command:

docker run -d -p 8000:80 healthcheckdemo
Docker Run

To view the health status of the container, you can use the following command:

sudo docker ps -a

Include in the docker-compose file

You can put the health check command directly into the docker-compose file instead of Dockerfile, as in some cases we won't get access to the docker file health check.

wget

healthcheck:
  test: wget --no-verbose --tries=1 --spider http://localhost:80 || exit 1
  interval: 60s
  retries: 5
  start_period: 20s
  timeout: 10s

curl

healthcheck:
  test: curl --fail http://localhost:80 || exit 1
  interval: 60s
  retries: 5
  start_period: 20s
  timeout: 10s

Below is an example of a complete docker-compose file:

version: '3.4'
services:
  web:
    image: very-simple-web
    build:
      context: ./
      dockerfile: Dockerfile
    ports:
      - "127.0.0.1:8000:80"
    restart: unless-stopped
    healthcheck:
      test: curl --fail http://localhost:8000 || exit 1
      interval: 60s
      retries: 5
      start_period: 20s
      timeout: 10s

The docker curl command returns exit codes such as 0, 1, 2 or 3 and many more. If the application returns the status code 200, the docker curl command will return the exit code 0 and if it fails, it will return exit code 1.

If the command returns 2 or any other exit code docker takes it as an undefined behaviour and that is the reason we have written the curl command with || exit 1.

Hence, docker health check command will return healthy if the exit code is 0 and returns unhealthy if the exit code is 1.

To start the service defined in the docker-compose file you can run the following command:

docker-compose up -d

To check the list of containers that are running along with the status of it you can use the following command:

sudo docker ps -a
Docker Health Check

How to proceed if CURL/WGET does not work?

If curl and wget need to be installed if you are using an image that doesn't have them installed. An install command can be included in your Dockerfile to accomplish this.

RUN apt-get update && apt-get install -y wget curl

However, you might also want to keep in mind that adding curl or wget would also add those tools' attack surfaces. Creating your own program that you can include in the docker health check test command is a good approach.

Wrap-Up

To identify potential software bugs as early as possible, Docker health checks can be implemented quickly. Consider adding a health check to your next Dockerfile.

It is easier to diagnose a misbehaving container when it is marked with the HEALTHCHECK instruction. The reliability of the workload can be analyzed irrespective of the docker container's "running" status.

All commands that issue an exit code of 0 or 1 are compatible with health checks. To inspect web services and databases, you can use commands such as docker curl and ping. Create a dedicated script and embed it in your images for more advanced control.

The fact that your container is running does not necessarily mean that your application is running or that it behaves as designed. It is very easy to implement Docker health checks and you can detect inconsistent behavior before it gets out of hand.


Atatus : Infrastructure Monitoring

Identify and resolve performance issues that affect your business by having complete visibility into your infrastructure with Atatus’s Infrastructure monitoring. Improve efficiency by correlating application metrics, logs and traces to troubleshoot problems faster.

Track the availability of the servers, hosts, virtual machines and containers with the help of Atatus Infrastructure Monitoring. It allows you to monitor, quickly pinpoint and fix the issues of your entire infrastructure.

In order to ensure that your infrastructure is running smoothly and efficiently, it is important to monitor it regularly. By doing so, you can identify and resolve issues before they cause downtime or impact your business.

Infrastructure Monitoring

Your server and container utilization is summarized in one place, including CPU, memory, disk, and network usage. Monitoring the health (uptime) of your servers' apps or services can be accomplished through health checks. Be notified with every impact on the services.

It is possible to determine the host, container, or other backend component that failed or experienced latency during an incident by using an infrastructure monitoring tool. In the event of an outage, engineers can identify which hosts or containers caused the problem.

As a result, support tickets can be resolved more quickly and problems can be addressed more efficiently.

Get your app running faster and bug-free with Atatus, get started with a 14-day free trial!