Search code examples
dockerhealth-check

Does Docker healthcheck always have to be conditional?


I was recently reading up on the usage of healthchecks in Docker. I was trying to understand the limits of healthchecks in general and just had a question if Docker healthchecks always needed to be conditional.

I was thinking because healthchecks can be run at specific intervals of time, is it possible to use general commands like apt-get update or in general install new or update libraries being used inside the Docker image through healthcheck commands without actually triggering a condition where the healthchecks turns the container "unhealthy".

I know work like this can perhaps be automated with including cronjobs in Dockerfile, but I just got curious if it could be used in this manner as well as an alternative to perform repetitive tasks inside the containers like running a script at specific intervals without making the container unhealthy (the above example of installing of updating libraries is probably not a good example but still would love to know if that can be done as well).


Solution

  • Technically, yes: you only need to make sure that the command you specified always returns success, i.e., a exit code of 0.

    You could do this by wrapping your task in a custom script that always exits with success or using logical operators in the shell command line like this:

    HEALTHCHECK CMD apt-get update || exit 0
    

    But looking at your question, conceptually: no, absolutely not!

    First of all this totally undermines the intended use of healthchecks, which is to only execute small commands to determine the current health of the container - and not to execute arbitrarily long running commands for maintenance tasks (see also the timeout option to HEALTHCHECK).

    So this approach is an incredibly hacky misuse of the HEALTHCHECK directive. It could also cause you unexpected problems since your specified HEALTHCHECK may be overriden by child images or the configuration when starting your image.

    The correct way to run commands periodically would be to run a cron daemon or using a process manager or something similar.

    Second of all installing software updates inside a running container is very bad practice since (docker) containers are meant to be ephemeral. The correct way to update your software is to (update and) rebuild the images and recreate the containers from the new images. (Even after installing updates within a running container you would have to restart the container in order to actually load the updated executables!)

    If you find yourself in a situation leading you to "solutions" like this you probably need to rethink your overall architecture to better match the docker way^^