Docker Healthcheck Examples

Docker Healthcheck Examples

Posted by

This post is a summary of the work I’ve done to add a HEALTHCHECK to several projects.

 

Adding HEALTHCHECK to a regular web server

Before adding a health check command, you need to make sure you have the wget, or curl installed inside your web server container.

You can do it by adding this or similar command to your project Dockerfile:

RUN apt update ; DEBIAN_FRONTEND=noninteractive apt install -y wget

You need to have a URL to check if your server is alive. In my case, it’s localhost:8080/alive.

I added the following line to the Dockerfile:

HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 CMD \
wget -O /dev/null localhost:8080/alive

In case you do not have wget in your container, you can use curl:

HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 CMD \
curl -o /dev/null localhost:8080/alive || true

 

Checking Java actuator health status

Add this or similar line to Dockerfile

HEALTHCHECK --interval=10s --timeout=3s --start-period=150s --retries=3 CMD \
[ $(wget -O - -o /dev/null localhost:8087/actuator/health | jq -r ".status") = "UP" ]

Add this or similar section to docker-compose file

    healthcheck:
      test: [ "CMD-SHELL", "[ $$(wget -O - -o /dev/null localhost:8185/actuator/health | jq -r '.status') = 'UP' ]" ]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 30s

Adding HEALTHCHECK to a custom Postgresql container

HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 CMD pg_isready

Adding HEALTHCHECK to a custom Cassandra container

HEALTHCHECK --interval=10s --timeout=3s --start-period=150s --retries=3 CMD \
[ $(nodetool statusgossip) = "running" ]

Same for implementing with docker-compose.yaml
healthcheck:
test: ["CMD-SHELL", "[ $$(nodetool statusgossip) = running ]"]

Adding HEALTHCHECK to custom Redis container

You can modify docker compose file and add a “healthcheck:” section. For example:

    healthcheck:
      test: [ "CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "--raw", "incr", "DockerHealthcheck" ]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 30s

Dump all running containers + health check status

Use the following command: docker ps –format “table {{.Names}}\t{{.Status}}”

NAMES STATUS
airflow-webserver Up 8 minutes (healthy)
airflow-worker Up 8 minutes (healthy)
airflow-scheduler Up 8 minutes (healthy)
airflow-triggerer Up 8 minutes (healthy)
cloud-web Up 9 minutes (healthy)
rundeck Up 9 minutes (healthy)
airflow-redis Up 10 days (healthy)
airflow-postgres Up 10 days (healthy)

Health check for multiple projects using the same Dockerfile

The solution here is to implement healthcheck on the level of docker compose project

Listen for docker health events

docker events --filter event=health_status