Created
June 13, 2024 09:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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