Last active
April 7, 2025 16:53
-
-
Save alisafariir/48263147f9b7e489e8f2a7d11ca8f286 to your computer and use it in GitHub Desktop.
Set Up Docker Containers Alerts on Telegram
This file contains hidden or 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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Running as Background Service
For persistent monitoring, create a systemd 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
sudo systemctl daemon-reload sudo systemctl enable docker-monitor.service sudo systemctl start docker-monitor.service