Jump to content

Restart Docker containers automatically


FunkyBuddha

Recommended Posts

Posted

Occasionally, a container would exit. Here's a script you can use in a Cron job to auto-restart containers.

What it does:

  • Checks for any containers that have an exit status
  • Loop through all the containers that exited
  • Issue a docker restart command
  • Check the status of the container after restart
  • Provide feedback if restart was successful or otherwise

 

Bash Script:

Quote

restart_containers() {
        for i in $(sudo docker ps -a --filter status=exited --format "{{.Names}}");
        do
            local c_nm=$i
            sudo docker restart $c_nm
            sleep 3
            local emsg=$(docker ps -a --filter name=$c_nm --format "{{.Names}} - {{.Status}}")
            local rc1=$(echo $emsg | grep Exit > /dev/null; echo $?)
            if [[ $rc1 -ne 0 ]]; then
                echo "RESTARTED - $c_nm"
            else
                echo "RESTART FAILED - $c_nm"
            fi
        done
}

 

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
×
×
  • Create New...