brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: --restart on-failure:5 gives up after five crashes

Docker
~/tips/tip-docker-run-restart-on-failure

docker run -d --name worker --restart=on-failure:5 example/worker:1.0

Restarts a container only after errors, and stops trying after a set number of attempts.

A container that crashes on start and gets restarted forever fills the logs and eats CPU. The on-failure policy with a number puts a limit on the loop.

The restart policies in the docker run reference are no (the default), on-failure[:max-retries], always and unless-stopped. With on-failure the container restarts only when it exits with a non-zero exit code, and :max-retries caps the attempts. The docs show --restart=on-failure:10 redis as the example.

docker run -d --name worker --restart=on-failure:5 example/worker:1.0

Docker waits between attempts. The delay starts at 100 ms, doubles each time and tops out at one minute, and it resets once a restarted container has been up for at least ten seconds. So five retries pass quickly, and then the container stays stopped with its last exit code. docker ps -a shows it as exited, and docker logs worker still has the error.

The docs add two caveats. A restart caused by the daemon starting up does not count under on-failure, so this policy will not bring the container back after a reboot of the host. For a service that must be there after a reboot, unless-stopped is the better choice, even if it means a crash loop needs your attention. A clean exit with code 0 is not a failure either, so a worker that quits politely stays down.

Further reading: docker run reference: restart policies

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link