5

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?

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82
john mich
  • 2,477
  • 3
  • 17
  • 32

1 Answers1

9

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.

Hans Kilian
  • 18,948
  • 1
  • 26
  • 35
  • 1
    Thank you so much, Hans, though it is hacky it has saved me from a lot of trouble. You should definitely be proud of it. Thank you for your amazing response. – john mich Aug 26 '21 at 08:28
  • Just out of curiosity- Docker inspect gives a more accurate status of the health within its JSON structure (Health.status = healthy), would you know if there is a file where docker stores this status, and you can simply retrieve it and throw it on proc/1/fd/1? – john mich Aug 26 '21 at 08:35
  • 1
    I don't think so. The detailed health status is only known to Docker which means that it's held outside the container. I don't know of a way you could get hold of it from inside the container and put it into the logs. – Hans Kilian Aug 26 '21 at 08:40
  • 1
    @HansKilian You may run docker commands from within a docker container but you need to give it the access to the `/var/run/docker.sock` socket. See answers for this [question](https://stackoverflow.com/questions/53126950/permission-denied-to-docker-daemon-socket-at-unix-var-run-docker-sock) – Jimmix Apr 01 '22 at 09:04