Docker – The HEALTHCHECK instruction

How to set a static IP address on Windows Server 2019

The HEALTHCHECK instruction, which is a fairly new addition to the Dockerfile, is used to define the command to run inside a container to test the container’s application health. When a container has a HEALTHCHECK, it gets a special status variable. Initially, that variable will be set to starting. Any time a HEALTHCHECK is performed successfully, the status will be set to healthy. When a HEALTHCHECK is performed and fails, the fail count value will be incremented and then checked against a retries value. If the fail count equals or exceeds the retries value, the status is set to unhealthy. The syntax of the HEALTHCHECK instruction is as follows:

# HEALTHCHECK instruction syntax
HEALTHCHECK [OPTIONS] CMD command (check container health by running a command inside the container)
HEALTHCHECK NONE (disable any HEALTHCHECK inherited from the base image)

There are four options that can be used when setting the HEALTHCHECK, and these options are as follows:

--interval=DURATION (default: 30s)
--timeout=DURATION (default: 30s)
--start-period=DURATION (default: 0s)
--retries=N (default: 3)

The --interval option allows you to define the amount of time between the HEALTHCHECK tests. The --timeout option allows you to define the amount of time that is considered too long for a HEALTHCHECK test. If the timeout is exceeded, the test is automatically considered a failure. The --start-period option allows for the definition of a no-fail time period during the container startup. Finally, the --retries option allows you to define how many consecutive failures it takes to update the HEALTHCHECK status to unhealthy.

The CMD part of the HEALTHCHECK instruction follows the same rules as the CMD instruction. Please review the preceding section regarding the CMD instruction for complete details. The CMD that is used will provide a status when it exits, which will be either a 0 for success or a 1 for fail. Here is a Dockerfile example that uses the HEALTHCHECK instruction:

# HEALTHCHECK instruction Dockerfile for Docker Quick Start
FROM alpine
RUN apk add curl
EXPOSE 80/tcp
HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost/ || exit 1
CMD while true; do echo 'DQS Expose Demo' | nc -l -p 80; done

Running a container from an image built with the preceding Dockerfile looks like this:

You can see that the HEALTHCHECK initially reported a status of starting, but once the HEALTHCHECK CMD reported success, the status updated to healthy.

Comments are closed.