Self-hosting mission-critical business tools—such as n8n workflow engines, Supabase backends, Redis queues, and Server-Side GTM containers—slashes monthly SaaS expenditures by over 80%. However, running self-hosted infrastructure introduces a dangerous operational vulnerability: silent container failure. If an out-of-memory (OOM) leak or disk saturation abruptly crashes your webhook container at 2:00 AM, you often remain unaware until high-value customer leads or payment events are permanently lost.

While enterprise monitoring tools like Datadog and New Relic charge exorbitant monthly fees per host, you can establish an enterprise-grade, zero-cost monitoring and self-healing pipeline using native Docker HEALTHCHECK directives, the Autoheal container engine, and a lightweight Telegram alert webhook watchdog.
This production blueprint provides the complete, copy-pasteable configuration to automate self-healing restarts and deliver instant mobile notifications whenever a container becomes unhealthy.
For the overarching system architecture connecting Linux compute, database persistence, and automated failover, read our master blueprint on Self-Hosted Business Infrastructure (2026): Ditching Cloud SaaS Fees Without Downtime.
System Architecture: The 3-Tier Failover Engine
This automated failover pipeline operates across three decoupled layers:
- Container Health Testing: Native Docker
HEALTHCHECKparameters poll internal application endpoints every 10 to 30 seconds. - Automated Container Recovery: An isolated
autohealsidecar monitors the Docker socket and automatically restarts any container that transitions into anunhealthystate. - Instant Webhook Alerting: A lightweight bash watchdog script running via crontab checks resource thresholds (RAM, CPU, and Disk usage >85%) and dispatches formatted alerts directly to your personal Telegram or Discord channel.
Step 1: Configuring Docker Healthchecks & Autoheal
To enable self-healing, your containers must report their internal status to the Docker daemon. Below is an optimized docker-compose.yml illustrating an n8n container, a PostgreSQL 16 database, and the Autoheal recovery container:
version: '3.8'
services:
# Automated Self-Healing Watchdog Container
autoheal:
image: willfarrell/autoheal:latest
restart: always
environment:
- AUTOHEAL_CONTAINER_LABEL=all
- AUTOHEAL_INTERVAL=10
- AUTOHEAL_START_PERIOD=30
volumes:
- /var/run/docker.sock:/var/run/docker.sock
# Production n8n Container with Healthcheck
n8n:
image: docker.n8n.io/n8nio/n8n:latest
restart: always
environment:
- N8N_PORT=5678
- NODE_OPTIONS=--max-old-space-size=3072
healthcheck:
test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost:5678/healthz || exit 1"]
interval: 15s
timeout: 5s
retries: 3
start_period: 30s
labels:
- "autoheal=true"
# PostgreSQL Database Container with pg_isready Healthcheck
postgres:
image: postgres:16-alpine
restart: always
environment:
- POSTGRES_USER=prod_admin
- POSTGRES_PASSWORD=SECURE_PASSWORD_HERE
- POSTGRES_DB=prod_db
healthcheck:
test: ["CMD-SHELL", "pg_isready -U prod_admin -d prod_db || exit 1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 20s
labels:
- "autoheal=true"
If an n8n workflow experiences an memory exhaustion spike and ceases responding on /healthz, Docker marks the container unhealthy after 3 consecutive failures. The autoheal container instantly intercepts this event via the Docker socket and restarts the service within seconds. To prevent memory leaks in data pipelines, review our guide on fixing n8n Out of Memory (OOM) errors.
Step 2: Creating Your Telegram Alert Bot in 60 Seconds
Telegram provides the most reliable mobile push notification infrastructure for system alerts with zero rate limits on personal channels:
- Open Telegram and search for @BotFather. Send
/newbotand follow the prompts to name your bot (e.g.MyServerWatchdogBot). Copy the provided HTTP API Token (e.g.7192837482:AAHj-SampleTokenHere). - Start a chat with your newly created bot by clicking “Start”.
- Search for @userinfobot in Telegram and click “Start”. Copy your numeric Id (e.g.
123456789). This is yourTELEGRAM_CHAT_ID.
Step 3: The Production Telemetry Watchdog Script
Create a dedicated script on your VPS at /opt/scripts/docker_watchdog.sh. This script inspects container health states, evaluates disk space thresholds, and checks available RAM:
#!/bin/bash
# ==============================================================================
# Zelobiz Production Docker Watchdog & Telegram Alert Engine
# ==============================================================================
BOT_TOKEN="YOUR_TELEGRAM_BOT_TOKEN_HERE"
CHAT_ID="YOUR_TELEGRAM_CHAT_ID_HERE"
HOSTNAME=$(hostname)
send_telegram() {
local message="$1"
curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" -d chat_id="${CHAT_ID}" -d text="${message}" -d parse_mode="HTML" > /dev/null
}
# 1. Check for Unhealthy or Stopped Containers
UNHEALTHY_CONTAINERS=$(docker ps -a --filter health=unhealthy --format "{{.Names}}")
EXITED_CONTAINERS=$(docker ps -a --filter status=exited --format "{{.Names}} (Code: {{.Status}})")
if [ -n "$UNHEALTHY_CONTAINERS" ]; then
MSG="🚨 DOCKER ALERT: Unhealthy Container Detected!%0AHost: ${HOSTNAME}%0AContainers:%0A${UNHEALTHY_CONTAINERS}%0AAutoheal is initiating container restart..."
send_telegram "$MSG"
fi
if [ -n "$EXITED_CONTAINERS" ]; then
MSG="⚠️ DOCKER WARNING: Exited Containers!%0AHost: ${HOSTNAME}%0AContainers:%0A${EXITED_CONTAINERS}"
send_telegram "$MSG"
fi
# 2. Check Disk Space Threshold (> 85%)
DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')
if [ "$DISK_USAGE" -gt 85 ]; then
MSG="🔴 CRITICAL DISK ALERT: Storage at ${DISK_USAGE}%%0AHost: ${HOSTNAME}%0AImmediate action required: run 'docker system prune -af'"
send_telegram "$MSG"
fi
# 3. Check Available RAM (< 10%)
FREE_RAM_PERCENT=$(free | awk '/Mem:/ {printf("%.0f"), $7/$2 * 100}')
if [ "$FREE_RAM_PERCENT" -lt 10 ]; then
MSG="⚠️ HIGH MEMORY ALERT: Available RAM is ${FREE_RAM_PERCENT}%%0AHost: ${HOSTNAME}%0APotential memory leak in running containers."
send_telegram "$MSG"
fi
Make the script executable with chmod +x /opt/scripts/docker_watchdog.sh. To explore alternatives using Discord webhooks or database health queries, see our tutorial on PostgreSQL health monitoring via Discord webhooks.
Step 4: Scheduling & Failure Verification
Open your crontab using crontab -e and configure the watchdog script to execute every 60 seconds:
# Run Docker Watchdog every 60 seconds
* * * * * /opt/scripts/docker_watchdog.sh > /dev/null 2>&1
Testing the Failover Pipeline
To verify that your alerting pipeline functions before relying on it in production, simulate a sudden container failure by manually stopping a running service:
docker stop n8n
Within 60 seconds, your Telegram client will chime with a formatted alert displaying the hostname, container name, and exit code. Restart the container with docker start n8n to restore normal operation.
5. Best Practices for Rock-Solid Production VPS Hosting
To guarantee that your self-hosted automation infrastructure remains online indefinitely without unexpected downtime:
- Schedule Weekly Docker Prunes: Old unused Docker images consume gigabytes of storage. Add
0 3 * * 0 docker system prune -af > /dev/null 2>&1to your crontab to clean up unused images every Sunday night. - Automate Offsite Database Backups: Self-healing restarts recover from crashes, but disk corruption requires database restoration. Ensure you run automated daily backups to S3 as detailed in our guide on automating PostgreSQL backups to AWS S3.
- Host on Reliable, Fixed-Cost Compute: Run your production containers on dedicated cloud infrastructure like Hetzner Cloud (€4.49/mo) to avoid unpredictable auto-scaling bills. Compare architectures in our benchmark on Self-Hosted n8n on Hetzner vs n8n Cloud or audit your software expenditure with our SaaS Cost & Lifetime Savings Calculator.
For more production automation blueprints and self-hosted developer systems, browse our complete Automation Hub.