How to log docker healthcheck status in docker logs?

Viewed 1015

Objective

I want to check if my docker container is healthy or not by verifying the docker logs.

Requirements

I have two files namely Dockerfile and loop.sh and I have added a HEALTHCHECK to my docker as follows:

Dockerfile

FROM alpine
ADD . /
HEALTHCHECK --interval=1s --timeout=30s --retries=3 CMD echo {'health':'healthy'}
CMD ["sh","loop.sh"]

loop.sh

#!/bin/sh

while 1>0;do echo "1"; sleep 2; done;

Observation

  • Observation 1

The docker logs just outputs the integer 1 as mentioned in the loop.sh but do not outputs the health status of my docker. An image is attached below-
Output of docker logs

  • Observation 2

The docker ps command shows that the container is healthy and hence deducing that my healthcheck is working. Please find the attached image below-

Output of Docker ps command

  • Observation 3

The docker inspect command also shows the health status of the docker container. Please find the screenshot below-
Health status

Problem

How to log this {'health':'healthy'} healthcheck status so that it can be seen in the docker logs?

1 Answers

OK, this is super hacky and I'm not proud of it. The issue is that the healthcheck runs in a different process than your main process, so it's hard to write to the main process' stdout.

But you can exploit that the main process (usually) runs as process #1 and write to /proc/1/fd/1 which is that process' stdout. Something like this

FROM ubuntu
HEALTHCHECK --interval=1s --timeout=30s --retries=3 CMD echo {'health': 'healthy'} | tee /proc/1/fd/1
CMD tail -f /dev/null

The tail -f /dev/null is just a dummy command that keeps the container running.

Related