Skip to content
Rishad Rahman
All work

Networking · DevOps project

ServerWatch

Infrastructure monitoring and automated email alerting with Prometheus, Grafana and Alertmanager, running in Docker on WSL2, with every alert tested by a controlled incident.

Stack

  • Prometheus
  • Grafana
  • Alertmanager
  • Docker Compose
  • Python
  • Flask
  • Bash
  • WSL2
alert rules, each with a runbook section
6
alert rules, each with a runbook section
dashboard panels, provisioned from files
9
dashboard panels, provisioned from files
alert tests sent FIRING and RESOLVED emails
5 / 5
alert tests sent FIRING and RESOLVED emails
RAM for the whole stack when idle
~300 MB
RAM for the whole stack when idle
The ServerWatch Grafana dashboard: three green UP tiles for prometheus, serverwatch-app and node, 9 hours of uptime, a 5.5% disk gauge, and time-series panels for CPU, memory, network, HTTP request rate, p50/p95 response time and error rate, with red dashed alert thresholds.

What it does

ServerWatch watches a machine and an application running on it. Prometheus scrapes Node Exporter for CPU, memory, disk, network and uptime, and a small Flask app for request rate, 5xx error rate, response time and availability, every 15 seconds. Grafana shows it all on one live dashboard. When something stays wrong for long enough, Alertmanager sends an email, and a second one when it is fixed.

ServicePortRole
Prometheus 3.59090Scrapes metrics, stores them for 2 days, evaluates alert rules
Node Exporter 1.99100System metrics for the WSL2 host
Flask app5000Demo application instrumented with prometheus-client
Alertmanager 0.289093Groups alerts and sends email over Gmail SMTP
Grafana 12.23000Dashboard, provisioned automatically on start-up

All five run with docker compose up -d on Docker Engine inside WSL2 (no Docker Desktop). Every red dashed line on the dashboard is the threshold of an alert rule, so what you see and what pages you agree.

Prometheus target health page: node, prometheus and serverwatch-app scrape pools, each 1/1 up, with last scrape times and durations.
All three scrape targets healthy in Prometheus.

Instrumenting the app

The Flask app uses all four Prometheus metric types: a Counter for requests by method, endpoint and status, a Histogram for latency, a Gauge for requests in flight and an Info metric for the version. Request hooks time every request except /metrics itself. The endpoint label is the route pattern rather than the raw URL, so random 404 paths can't create thousands of time series:

REQUEST_LATENCY = Histogram(    "serverwatch_http_request_duration_seconds",    "HTTP request duration in seconds.",    ["method", "endpoint"],    buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0),)…def endpoint_label():    # Unknown URLs are grouped as 'unmatched' so random 404 paths    # can't create thousands of separate time series.    rule = request.url_rule    return rule.rule if rule else "unmatched"…@app.teardown_requestdef finish_request(_error):    # Runs even if the request crashed, so the gauge never gets stuck.    if g.pop("tracked", False):        IN_PROGRESS.dec()

The app runs under Gunicorn in a slim image as a non-root user, with a Docker health check. Setting CHAOS_ENABLED=true turns on two test switches, ?fail=1 for an HTTP 500 and ?delay=2 for a slow response (capped at 5 s), which the incident simulations use.

Alert rules

Six rules cover availability, the host and the application. Each has a severity and a for: duration, so a short spike doesn't send an email, and a runbook annotation that links the email to the right recovery steps.

AlertSeverityConditionFor
TargetDowncriticalA scrape target is unreachable (up == 0)1m
HighErrorRatecriticalOver 5% of requests return 5xx, with traffic above 0.1 req/s2m
SlowResponseTimewarningp95 latency over 1 s, excluding /health3m
HighCpuUsagewarningCPU over 85%5m
HighMemoryUsagewarningMemory over 85%5m
HighDiskUsagewarningRoot filesystem over 80%10m

The error-rate rule only fires when there is real traffic, so one failed request during a quiet minute (1 of 1 = 100%) doesn't page anyone:

prometheus/alert_rules.ymlSource (opens GitHub in a new tab)
- alert: HighErrorRate  expr: |    (      100 * sum(rate(serverwatch_http_requests_total{job="serverwatch-app",status=~"5.."}[2m]))        / sum(rate(serverwatch_http_requests_total{job="serverwatch-app"}[2m]))    ) > 5    and sum(rate(serverwatch_http_requests_total{job="serverwatch-app"}[2m])) > 0.1  for: 2m  labels:    severity: critical  annotations:    summary: 'High HTTP error rate on serverwatch-app: {{ printf "%.1f" $value }}%'    runbook: 'docs/runbook.md#higherrorrate'

Testing every alert

An alert that has never fired is an alert you can't trust. scripts/simulate.sh creates safe, time-limited incidents (1 to 15 minutes, stoppable with Ctrl+C), and simulate.sh status prints key metrics and any pending or firing alerts. Every path was run end to end on 17 November 2026:

AlertHow it was triggeredResult
Test notificationA test alert sent straight to Alertmanager with amtoolFIRING and RESOLVED emails
TargetDownApp container stopped for 4 minutesFired after ~1.5 min; RESOLVED after restart
HighErrorRatesimulate.sh errors 5: ~33% HTTP 500 for 5 minutesFired; RESOLVED when the test ended
SlowResponseTimesimulate.sh slow 6: 2 s responses for 6 minutesFired; RESOLVED when the test ended
HighMemoryUsageThreshold lowered from 85% to 10%, then restored with git checkout and a reloadFired; RESOLVED after the restore
Prometheus alerts page during a test: the availability group shows TargetDown FIRING in red, while the application and host rules are inactive.
TargetDown firing while the app is stopped
The alert email: a red header reading 1 alert for alertname=TargetDown severity=critical, a View In Alertmanager button, and the alert's labels, description and runbook link.
The FIRING email, with a link to the runbook

The CPU and disk alerts are deliberately not forced, since pushing a laptop's CPU past 85% or filling its disk is not a safe test. They share the same Prometheus → Alertmanager → email path proven above, their rules pass promtool check rules, and they can be checked with the same temporary-threshold method.

Secrets and an 8 GB laptop

Gmail credentials live only in .env, which Git ignores. alertmanager.yml holds placeholders, and a small entrypoint script checks that every variable is set, fills them in with sed, writes the result to a memory-only tmpfs and then starts Alertmanager. Gmail uses an App Password, config folders are mounted read-only, and Grafana sign-up, analytics and update checks are off.

The whole stack was built to run beside everything else on a laptop with 8 GB of RAM:

  • WSL2 capped at 3 GB RAM, 4 CPUs and 2 GB of swap through .wslconfig.
  • Per-container memory limits: Prometheus 512 MB, Grafana 384 MB, the app 128 MB, Alertmanager and Node Exporter 64 MB each.
  • Short retention: Prometheus keeps 2 days or 1 GB, Alertmanager 48 hours, and container logs are capped at 3 × 10 MB.
  • Result: about 250–300 MB of RAM for all five containers when idle, measured with docker stats.

What's next

  • Monitor the Windows host too, with windows_exporter.
  • Centralised logs with Loki, linked from the dashboard panels.
  • A Telegram or Slack notification channel next to email.
  • GitHub Actions that run promtool, amtool and docker compose config on every push.
↑ ↓ to move · Enter to open