Skip to content

Instantly share code, notes, and snippets.

@alisafariir
Last active April 7, 2025 16:53
Show Gist options
  • Save alisafariir/48263147f9b7e489e8f2a7d11ca8f286 to your computer and use it in GitHub Desktop.
Save alisafariir/48263147f9b7e489e8f2a7d11ca8f286 to your computer and use it in GitHub Desktop.
Set Up Docker Containers Alerts on Telegram
# create /usr/local/bin/monitor_docker.sh
# sudo chmod +x /usr/local/bin/monitor_docker.sh
#!/bin/bash
# Telegram bot settings
BOT_TOKEN="your_bot_token_here"
CHAT_ID="your_chat_id_here"
# Function to send Telegram message
send_notification() {
local event_type=$1
local container_name=$2
local additional_info=$3
case $event_type in
"start")
local emoji="🟢"
local action="Started"
;;
"stop")
local emoji="🔴"
local action="Stopped"
;;
"die")
local emoji="⚫"
local action="Crashed"
;;
"restart")
local emoji="🟡"
local action="Restarted"
;;
*)
local emoji="ℹ️"
local action="Event"
;;
esac
local message="${emoji} *Docker Container ${action}* ${emoji}
*Container:* ${container_name}
*Host:* $(hostname)
*Time:* $(date)"
# Add additional info if provided
if [ -n "$additional_info" ]; then
message="${message}
${additional_info}"
fi
curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" \
-d chat_id="${CHAT_ID}" \
-d text="${message}" \
-d parse_mode="Markdown"
}
# Monitor Docker events
docker events --format '{{json .}}' | while read -r event; do
status=$(echo "$event" | jq -r '.status')
container_name=$(echo "$event" | jq -r '.Actor.Attributes.name')
case $status in
"start")
send_notification "start" "$container_name"
;;
"stop")
send_notification "stop" "$container_name"
;;
"die")
exit_code=$(echo "$event" | jq -r '.Actor.Attributes.exitCode')
send_notification "die" "$container_name" "*Exit Code:* ${exit_code}"
;;
"restart")
send_notification "restart" "$container_name"
;;
# Add more event types if needed
esac
done
@alisafariir
Copy link
Author

Running as Background Service
For persistent monitoring, create a systemd service:

  1. Create service file /etc/systemd/system/docker-monitor.service:
sudo apt update
sudo apt install -y jq curl

nano /etc/systemd/system/docker-monitor.service
# /etc/systemd/system/docker-monitor.service

[Unit]
Description=Docker Container Monitor
After=docker.service

[Service]
ExecStart=/usr/local/bin/monitor_docker.sh
Restart=always
User=root

[Install]
WantedBy=multi-user.target
  1. Enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable docker-monitor.service
sudo systemctl start docker-monitor.service
  1. Testing the Solution:
docker run --name test-alpine -d alpine sleep 30
docker stop test-alpine

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