Skip to content

Instantly share code, notes, and snippets.

@casebeer
Last active January 21, 2025 00:56
Show Gist options
  • Save casebeer/25de4843da381018f4ec7b709a380492 to your computer and use it in GitHub Desktop.
Save casebeer/25de4843da381018f4ec7b709a380492 to your computer and use it in GitHub Desktop.
Ubuntu cron.hourly script to monitor and restart non-running Docker containers
#!/bin/sh
#
# Check on "running" status of critical Docker containers
# and restart them if they are not running.
#
# This is necessary because after a hard host machine reboot, many Docker containers will
# will not start cleanly. Since Docker restart policies and healthchecks only take effect
# once a container has successully started up once, these failed containers will never
# start.
#
# install in /etc/cron.hourly/docker-container-monitor-restart
criticalContainers="container1 container2 container3 container4"
for containerName in ${criticalContainers} ; do
containerStatus="$(/usr/bin/docker inspect --format '{{.State.Status}}' "${containerName}")"
if [ "${containerStatus}" != "running" ] ; then
/usr/bin/logger -t cron.hourly \
"Docker container ${containerName} is ${containerStatus}. Restarting ${containerName}..."
/usr/bin/docker restart "${containerName}" | /usr/bin/logger -t cron.hourly
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment