Skip to content

Instantly share code, notes, and snippets.

@iamtalhaasghar
Last active October 13, 2024 14:37
Show Gist options
  • Save iamtalhaasghar/8b049259f2d4fd33f5c38d7e4248ad73 to your computer and use it in GitHub Desktop.
Save iamtalhaasghar/8b049259f2d4fd33f5c38d7e4248ad73 to your computer and use it in GitHub Desktop.
a script to check docker containers status and if anyone is stopped then start it
#!/bin/bash
# a script to check docker containers status and if anyone is stopped then start it
# Author: Talha Asghar <[email protected]>
# Co-author: chatgpt.com
# 13th-October-2024
log_file='/var/log/dockerwatch.log'
log() {
local message="$1"
local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
# Log to screen
echo "$timestamp - $message"
# Log to file
echo "$timestamp - $message" >> "$log_file"
}
# get list of all stopped containers
# in case you want to exclude some containers
#containers=$(docker ps -aq -f "status=exited" | grep -v -e b4d05625b6d8 -e 193b3329e967 -e 97d65a75e41e -e 415678546ced)
containers=$(docker ps -aq -f "status=exited")
if [ -n "$containers" ]; then
# Get the names of the containers that will be started
container_names=$(docker ps -a --format '{{.Names}}' --filter "id=$containers")
log "Starting containers: $container_names"
docker start $containers
else
log "No containers to start."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment