How to auto restart a docker container with compose after reboot or failed attempt? How to auto restart a docker container with compose after reboot or failed attempt? docker docker

How to auto restart a docker container with compose after reboot or failed attempt?


Docker (docker-compose) will not help you directly in this task. The only thing that the docker orchestrator is doing is to recognize that the container had failed and to create new container to replace it.

Other orchestrators like Kubernetes have improved handling of the lifecycle, by allowing the orchestrator to recognize the internal state of the containers. Based on the internal state, the orchestrator will manage the lifecycle of that container and also the lifecycle of the related containers.

In your particular case, even just by moving to Kubernetes will not really help you, since it is container's task to recognize if he has all the resources ready to start working.

What you need to do is to create a startup script for the container that will recognize that all of the required resources are ready and it can proceed with the start. When you prepare the script, you can choose to exit from the script after waiting certain time (in which case Docker will detect it as container failure and will handle it based on restart rules) or to wait forever, until the resources are ready. I prefer the approach to wait for a while and then fail if resources are still not ready. This makes it more easier for the administrator to recognize that the container is not healthy.

Most trivial example of the script would be:

testfile="/dev/usbdrive/Iamthedrive.txt"while :do  if [ -e "$testfile" ]  then    echo "drive is mounted."    start_the_container_main_process.sh    exit(0)  fi  echo "drive is still not ready, waiting 10s"  sleep(10)done

Make sure you have sleep for certain amount of time to go easy on the system resources.