Skip to content

Instantly share code, notes, and snippets.

@samir64
Created June 13, 2024 09:02
Show Gist options
  • Save samir64/7566f50670d7e502df1524e2f8315a52 to your computer and use it in GitHub Desktop.
Save samir64/7566f50670d7e502df1524e2f8315a52 to your computer and use it in GitHub Desktop.
Restart a docker container by a part of its name when in last 200 line of its log has more than 150 times of specific message
#!/usr/bin/bash
if [ -z $1 ]; then
echo "Container name is empty"
exit -1
fi
if [ -z "$2" ]; then
echo "Message is empty"
exit -1
fi
container_name=$1
message=$2
containers=$(docker ps | grep -oE "[^ ]+$")
found_container=$(echo "$containers" | grep -E $1 | head -n 1)
while true; do
container_logs=$(docker logs -n 200 $found_container 2>&1)
filtered_logs=$(echo "$container_logs" | grep -iE -B1 "$message" | grep -E "^[^-]{2}")
bad_logs=$(echo "$filtered_logs" | grep -iE "$message")
filtered_logs_count=$(echo "$filtered_logs" | wc -l)
bad_logs_count=$(echo "$bad_logs" | wc -l)
echo "$filtered_logs_count"
echo "$bad_logs_count"
if [[ $filtered_logs_count -eq $bad_logs_count ]] && [[ $bad_logs_count -gt 150 ]]; then
docker restart $container_name
fi
sleep 10
done
# To run script use:
# chmod +x script.sh
# And then run:
# ./script.sh CONTAINER_NAME "MESSAGE"
@samir64
Copy link
Author

samir64 commented Jun 13, 2024

I found that we can use Docker health check and auto health service to do this job automatically.
For more information visit this links:
https://docs.docker.com/reference/dockerfile/#healthcheck
moby/moby#22719
https://github.com/willfarrell/docker-autoheal?tab=readme-ov-file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment