Sometimes, Docker containers fail silently or exit with a non-zero code that isn't caught by standard restart policies. But what happens when a container crashes or exits unexpectedly and --restart=always isn't enough?
In such cases, a custom Docker restart script can act as a watchdog to keep your containers alive and monitored.
Why Use a Restart Script Instead of Docker’s Built-in Policies?
While Docker’s --restart options like always, on-failure, or unless-stopped cover many scenarios, they fall short when:
- The Docker daemon itself crashes or restarts
- You want custom logging or notification when a container dies
- You’re using complex stacks and need to chain actions
That’s where a script comes in handy.
The Script: Restart Docker Containers Automatically
Here's a simple Bash script that monitors and restarts containers by name:
You can use nohup or a service file to start this script. Even you can add in cronjob on @reboot.
So it can start running on reboot. Like:
chmod +x docker-restart-watcher.sh
nohup ./docker-restart-watcher.sh &
nohup script_name.sh
or ./script_name.sh &
You can even monitor multiple containers by wrapping the check inside a loop over a list.
A More Advanced Version
Want to track multiple containers?
This is how you can restart your docker containers, even if it fails and you are not around.
Hope you find it helpful!!