Search code examples
dockercron

CRON Job to ping running container port and restart server in case of error


I have a python script running inside a docker container, with a REST API inside the container (localhost access to port from 8085)

Things work great (http://{host_ip_address:8085}), but once in a while the container stops responding to http requests, restarting the container solves the issue.

I'd like to setup a CRON job, within the host running the container, to check that http://localhost:8085 is responding, and if not, restart the container.

it is ok for me to restart all running containers on the machine, so the failure command can be:

docker restart $(docker ps -a -q)

How can I achieve this ?


Solution

  • Answering my own question:

    docker has the HEALTHCHECK instruction to poll the container via any command we want. unfortunately, at the time of writing, the container will not restart automatically if unhealthy.

    Here is my HEALTHCHECK instruction in Dockerfile (app is exposing port 8085):

    HEALTHCHECK --interval=1m --timeout=30s --start-period=45s \
        CMD curl -f --retry 6 --max-time 5 --retry-delay 10 --retry-max-time 60 "http://localhost:8085" || bash -c 'kill -s 15 -1 && (sleep 10; kill -s 9 -1)'