Automatically Restart a Failing Jenkins Docker Container with Bash and Cron
This guide explains how to create a Bash script that monitors a Jenkins Docker container, automatically restarts it when it stops, grant the script execution rights, and schedule it with cron to run every ten seconds, eliminating manual docker restart commands.
When a Jenkins container crashes due to insufficient CPU resources, manually restarting it with docker restart <container_id> is cumbersome. This article shows how to create a Bash script that checks the container’s status and restarts it automatically, grant execution permission, and schedule it with cron to run every 10 seconds.
Script to Detect and Restart the Container
#!/bin/bash
# Container name
CONTAINER_NAME="myjenkins"
check_and_restart_container() {
# Get container ID
CONTAINER_ID=$(docker ps -aqf "name=^${CONTAINER_NAME}$")
if [[ -z "$CONTAINER_ID" ]]; then
# Container does not exist, exit
exit 0
fi
# Check container status
STATUS=$(docker inspect -f '{{.State.Running}}' $CONTAINER_ID 2>/dev/null)
# If container is not running, restart it
if [[ "$STATUS" != "true" ]]; then
docker restart $CONTAINER_ID >/dev/null 2>&1
fi
}Grant Execution Permission
chmod +x /local/cron/check_and_restart_container.shAdd to Cron
Run the script every 10 seconds:
* * * * * /local/cron/check_and_restart_container.sh
* * * * * sleep 10 && /local/cron/check_and_restart_container.shLin is Dream
Sharing Java developer knowledge, practical articles, and continuous insights into computer engineering.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
