In modern server administration and self-hosting communities across Reddit (r/selfhosted) and Hacker News, managing server health without paying for expensive SaaS monitoring tools like Datadog or NewRelic has become a top priority. While web dashboards like Grafana or Netdata provide detailed metrics, they lack instantaneous mobile push alerts when critical failures occur. This is where building a self-hosted Telegram server and Docker monitoring bot becomes an game-changing solution: it transforms Telegram into a lightweight, real-time command center for your entire infrastructure.
You can build a production-grade Telegram server monitor in under 15 minutes using Python 3.11+, aiogram 3, psutil, and the Docker SDK for Python. The bot periodically checks CPU, RAM, and disk thresholds, monitors container health, sends red alert notifications when limits are breached, and provides interactive inline buttons to restart crashed containers directly from your phone. Explore top developer utilities in Telekit's Tech & Coding Directory.
Why Telegram is the Ultimate Server Monitoring Command Center in 2026
Traditional monitoring tools often require navigating heavy web UIs, managing complex authentication tokens, or maintaining dedicated browser tabs. A self-hosted Telegram bot provides a unified, cross-platform interface that works seamlessly on mobile devices, tablets, and desktop workstations without any additional app installations.
Prerequisites and Environment Requirements
Before beginning the installation, ensure your environment meets the following baseline setup requirements:
- Operating System: Ubuntu 22.04 LTS / 24.04 LTS, Debian 12, or any Linux distribution running Docker.
- Python Version: Python 3.10, 3.11, or 3.12 with
pipandvenvpackages installed. - Docker Engine: Docker CE installed and running with permissions to access
/var/run/docker.sock. - Telegram Bot Token: Created via Telegram's official @BotFather.
- Telegram User ID: Your numerical ID obtained from @userinfobot for security authorization.
Step 1: Environment Setup & Dependency Installation
Connect to your server via SSH and set up a dedicated directory for your monitoring agent. We will isolate dependencies using a Python virtual environment.
# 1. Create project directory and navigate inside mkdir -p ~/telegram-server-monitor cd ~/telegram-server-monitor # 2. Install python3-venv and system dependencies sudo apt update sudo apt install -y python3-pip python3-venv docker.io # 3. Create virtual environment and activate python3 -m venv venv source venv/bin/activate # 4. Install aiogram 3, psutil, docker SDK and python-dotenv pip install --upgrade pip pip install aiogram psutil docker python-dotenv
Step 2: Configuration & Security Environment File
Security is critical when creating a bot that can execute commands on your host system. We enforce strict user authorization by storing configuration variables in a .env file. Create the file using nano .env:
# .env configuration file BOT_TOKEN=7890123456:AAFxYzExampleToken123456789 ADMIN_USER_IDS=123456789,987654321 # Threshold Settings (%) CPU_ALERT_THRESHOLD=85 RAM_ALERT_THRESHOLD=90 DISK_ALERT_THRESHOLD=90 # Check Interval in seconds CHECK_INTERVAL=60
Step 3: Building the System Metrics Collector (metrics.py)
Create a dedicated module metrics.py using psutil to collect CPU usage, memory utilization, disk space, and top resource-consuming processes across the host system.
import psutil
import datetime
def get_system_status():
cpu_usage = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
uptime = str(datetime.datetime.now() - boot_time).split('.')[0]
return {
"cpu_usage": cpu_usage,
"ram_usage": memory.percent,
"ram_used_gb": round(memory.used / (1024**3), 2),
"ram_total_gb": round(memory.total / (1024**3), 2),
"disk_usage": disk.percent,
"disk_free_gb": round(disk.free / (1024**3), 2),
"disk_total_gb": round(disk.total / (1024**3), 2),
"uptime": uptime
}
def get_top_processes(limit=5):
processes = []
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent']):
try:
processes.append(proc.info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
sorted_procs = sorted(processes, key=lambda x: x['memory_percent'] or 0, reverse=True)
return sorted_procs[:limit]
Step 4: Creating the Docker Management Engine (docker_mgr.py)
The Docker engine module interfaces with the local Docker daemon socket (/var/run/docker.sock) to monitor active containers, fetch log snippets, and trigger container restarts.
import docker
class DockerManager:
def __init__(self):
try:
self.client = docker.from_env()
except Exception as e:
self.client = None
print(f"Docker init error: {e}")
def list_containers(self):
if not self.client:
return []
containers = self.client.containers.list(all=True)
result = []
for c in containers:
result.append({
"id": c.short_id,
"name": c.name,
"status": c.status,
"image": c.image.tags[0] if c.image.tags else "unknown"
})
return result
def restart_container(self, container_id):
if not self.client:
return False, "Docker client unavailable"
try:
container = self.client.containers.get(container_id)
container.restart(timeout=10)
return True, f"Container {container.name} restarted successfully."
except Exception as e:
return False, str(e)
def get_container_logs(self, container_id, tail=20):
if not self.client:
return "Docker client unavailable"
try:
container = self.client.containers.get(container_id)
logs = container.logs(tail=tail).decode('utf-8', errors='replace')
return logs if logs else "No logs found."
except Exception as e:
return f"Error fetching logs: {e}"
Step 5: Developing the Async Telegram Bot Core (main.py)
Now, write the primary entrypoint main.py using aiogram 3. This handles commands (/start, /status, /docker), renders interactive inline buttons, and enforces admin ID authorization checks.
import asyncio
import os
from dotenv import load_dotenv
from aiogram import Bot, Dispatcher, types, F
from aiogram.filters import Command
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from metrics import get_system_status, get_top_processes
from docker_mgr import DockerManager
load_dotenv()
TOKEN = os.getenv("BOT_TOKEN")
ADMIN_IDS = [int(i.strip()) for i in os.getenv("ADMIN_USER_IDS", "").split(",") if i.strip()]
CPU_THRESHOLD = float(os.getenv("CPU_ALERT_THRESHOLD", 85))
RAM_THRESHOLD = float(os.getenv("RAM_ALERT_THRESHOLD", 90))
DISK_THRESHOLD = float(os.getenv("DISK_ALERT_THRESHOLD", 90))
CHECK_INTERVAL = int(os.getenv("CHECK_INTERVAL", 60))
bot = Bot(token=TOKEN)
dp = Dispatcher()
docker_mgr = DockerManager()
def is_authorized(user_id: int) -> bool:
return user_id in ADMIN_IDS
@dp.message(Command("start"))
async def cmd_start(message: types.Message):
if not is_authorized(message.from_user.id):
return await message.answer("⚠️ Unauthorized user ID.")
keyboard = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text="📊 System Status", callback_data="system_status")],
[InlineKeyboardButton(text="🐳 Docker Containers", callback_data="docker_list")],
[InlineKeyboardButton(text="🔥 Top RAM Processes", callback_data="top_procs")]
])
await message.answer(
"⚡ Server & Docker Monitor Active
"
"Welcome! Use the menu below to view real-time host telemetry and container statuses.",
parse_mode="HTML",
reply_markup=keyboard
)
@dp.callback_query(F.data == "system_status")
async def cb_status(callback: types.CallbackQuery):
if not is_authorized(callback.from_user.id):
return await callback.answer("Unauthorized", show_alert=True)
status = get_system_status()
text = (
f"🖥️ Host System Status
"
f"━━━━━━━━━━━━━━━━━━━
"
f"CPU Usage: {status['cpu_usage']}%
"
f"RAM Usage: {status['ram_usage']}% ({status['ram_used_gb']} GB / {status['ram_total_gb']} GB)
"
f"Disk Space: {status['disk_usage']}% ({status['disk_free_gb']} GB free)
"
f"Uptime: {status['uptime']}
"
)
kb = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text="🔄 Refresh", callback_data="system_status")]
])
await callback.message.edit_text(text, parse_mode="HTML", reply_markup=kb)
@dp.callback_query(F.data == "docker_list")
async def cb_docker(callback: types.CallbackQuery):
if not is_authorized(callback.from_user.id):
return await callback.answer("Unauthorized", show_alert=True)
containers = docker_mgr.list_containers()
if not containers:
return await callback.message.edit_text("No Docker containers found.")
buttons = []
for c in containers:
icon = "🟢" if c['status'] == 'running' else "🔴"
buttons.append([InlineKeyboardButton(
text=f"{icon} {c['name']} ({c['status']})",
callback_data=f"container_{c['id']}"
)])
buttons.append([InlineKeyboardButton(text="🔄 Refresh List", callback_data="docker_list")])
kb = InlineKeyboardMarkup(inline_keyboard=buttons)
await callback.message.edit_text("🐳 Active Docker Containers:", parse_mode="HTML", reply_markup=kb)
@dp.callback_query(F.data.startswith("container_"))
async def cb_container_detail(callback: types.CallbackQuery):
c_id = callback.data.split("_")[1]
kb = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text="♻️ Restart Container", callback_data=f"restart_{c_id}")],
[InlineKeyboardButton(text="📜 View Logs (Tail 20)", callback_data=f"logs_{c_id}")],
[InlineKeyboardButton(text="⬅️ Back to Containers", callback_data="docker_list")]
])
await callback.message.edit_text(f"⚙️ Container Actions: {c_id}", parse_mode="HTML", reply_markup=kb)
@dp.callback_query(F.data.startswith("restart_"))
async def cb_restart_container(callback: types.CallbackQuery):
c_id = callback.data.split("_")[1]
success, msg = docker_mgr.restart_container(c_id)
await callback.answer(msg, show_alert=True)
async def background_alert_loop():
while True:
try:
status = get_system_status()
alerts = []
if status['cpu_usage'] >= CPU_THRESHOLD:
alerts.append(f"🔥 CRITICAL CPU ALERT: {status['cpu_usage']}%")
if status['ram_usage'] >= RAM_THRESHOLD:
alerts.append(f"⚠️ HIGH RAM ALERT: {status['ram_usage']}%")
if status['disk_usage'] >= DISK_THRESHOLD:
alerts.append(f"💾 DISK SPACE CRITICAL: {status['disk_usage']}% used")
if alerts:
alert_text = "🚨 SERVER THRESHOLD BREACH
" + "
".join(alerts)
for admin_id in ADMIN_IDS:
try:
await bot.send_message(admin_id, alert_text, parse_mode="HTML")
except Exception as e:
print(f"Failed alert send to {admin_id}: {e}")
except Exception as e:
print(f"Background check error: {e}")
await asyncio.sleep(CHECK_INTERVAL)
async def main():
asyncio.create_task(background_alert_loop())
print("Bot started monitoring system...")
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())
Step 6: Production Deployment via Systemd Service
To ensure your monitoring bot starts automatically when your server boots up and restarts immediately if crashed, configure a systemd service file at /etc/systemd/system/telegram-monitor.service:
# Create systemd service file sudo nano /etc/systemd/system/telegram-monitor.service [Unit] Description=Telegram Server & Docker Monitor Bot After=network.target docker.service [Service] Type=simple User=root WorkingDirectory=/root/telegram-server-monitor ExecStart=/root/telegram-server-monitor/venv/bin/python main.py Restart=always RestartSec=5 [Install] WantedBy=multi-user.target
Enable and start the service with the following terminal commands:
# Reload systemd, enable service on boot, and start sudo systemctl daemon-reload sudo systemctl enable telegram-monitor sudo systemctl start telegram-monitor # Verify running status sudo systemctl status telegram-monitor
Alternative Deployment: Docker Compose Containerization
If you prefer running all applications inside Docker containers, you can containerize the bot itself using the following docker-compose.yml file:
version: '3.8'
services:
telegram-monitor:
build: .
container_name: telegram_monitor_bot
restart: always
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- /proc:/host/proc:ro
env_file:
- .env
Frequently Asked Questions (FAQ)
How do I find my numeric Telegram User ID for security whitelisting?
Open Telegram and search for @userinfobot. Send any message or type /start. The bot will return your numeric user ID (e.g. 123456789). Add this number to ADMIN_USER_IDS in your .env file.
Is mounting /var/run/docker.sock into a bot script safe?
Access to docker.sock effectively provides root equivalent access on the host system. To keep it secure, ensure your Telegram bot token is never checked into public GitHub repositories, and enforce strict user ID authorization checks in code as shown in Step 5.
Can this bot monitor remote VPS servers or multiple hosts?
Yes. You can either deploy an instance of the bot on each VPS or configure the primary bot to poll remote Docker engines over secure TLS sockets or SSH tunnels.
How much RAM does this Python server monitoring bot consume?
Because aiogram 3 and psutil are highly optimized asynchronous libraries, the entire process consumes between 25MB and 35MB of RAM, making it suitable even for $4/mo entry-level cloud instances.
Conclusion
Building a self-hosted Telegram server and Docker monitoring bot gives devops engineers and self-hosters real-time visibility, automated push alerts, and direct container management capabilities without ongoing subscription fees. By following this guide, you now have a fully secure, customizable monitoring platform running on your Linux host. Explore more open-source tools and developer channels in Telekit's Developer Catalog today!