Skip to content

Instantly share code, notes, and snippets.

@gilangvperdana
Created February 8, 2023 18:30
Show Gist options
  • Save gilangvperdana/4a2fa0d5d0a9689dea561437b9abec6e to your computer and use it in GitHub Desktop.
Save gilangvperdana/4a2fa0d5d0a9689dea561437b9abec6e to your computer and use it in GitHub Desktop.
Alert when Docker Container Restart Frequently

Goals

  • ALerting when docker container restarting > 3
  • Restart container automaticly

alert sh Script

nano alert.sh
#!/bin/bash

# Define the Telegram Bot API token and chat ID
BOT_API_TOKEN="YOUR_API_TOKEN"
CHAT_ID="YOUR_CHAT_ID"

# Function to send the message to Telegram
send_message () {
  curl -s -X POST https://api.telegram.org/bot$BOT_API_TOKEN/sendMessage -d chat_id=$CHAT_ID -d text="$1" -d parse_mode=markdown
}

# Define the threshold for the number of restarts
THRESHOLD=3

# Get the list of running Docker containers
containers=$(docker ps -q)

# Loop through the list of containers
for container in $containers
do
  # Get the number of restarts for each container
  restarts=$(docker inspect --format='{{.RestartCount}}' $container)
  # Get name of container
  name=$(docker inspect --format='{{.Name}}' $container | tr -d '/')
  # Get Image of container
  image=$(docker inspect --format='{{.Config.Image}}' $container)
  # Get Hostname name
  hostname=$(cat /proc/sys/kernel/hostname)
  # Get Date
  dates=$(date)
  if [ "$restarts" -ge "$THRESHOLD" ]
  then
    # If the number of restarts is greater than or equal to the threshold, send a message to Telegram
    send_message "*ALERTING,*%0ADocker container on %0A %0A *Instance: $hostname * %0A *Name: $name * %0A *Image: $image * %0A *Date: $dates * %0A %0A is restarting too many times, Please check!"
	docker restart $container
  fi
done
chmod +x alert.sh

crontab Configuration

crontab -e
* * * * * /bin/bash /root/alert.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment