Ravindra BagaleCourses & study guides मराठी

Chapter 13: Monitoring Basics

DevOps

13.13 Lab — disk metric path and a triggered alert

Why: the problem

This is the final lab of the chapter. You will be the DevOps engineer for a small "badge API" used by an Instagram-style app. The manager gives you one clear job: "Before Diwali traffic, I want a dashboard and one alert that will warn us before the disk fills up, and I want proof that it works." That is what real teams ask for. Not a slide, not a definition, but a working path: the server sends numbers, Prometheus stores them, Grafana shows them, an alert fires on a full disk, a message reaches the team, and it resolves when fixed. You will build all of it from an empty folder, break it on purpose, and write the runbook. When you finish, you can say in an interview: "I built and tested a full Prometheus and Grafana monitoring stack with alerting."

What we will build

You will build one folder with everything: a tiny badge API in Python with /metrics, Node Exporter, Prometheus with rules, Alertmanager sending to a local webhook receiver (so you need no Slack account), and Grafana with a provisioned dashboard. Then you will fill the disk, watch the alert fire and reach the receiver, clean up, and watch it resolve. Last, you will write the same disk alarm for CloudWatch so you know both paths.

What: every term in plain English

  • Lab — A safe practice setup you can break and delete.
  • Webhook receiver — A small web app that receives alert messages from Alertmanager as JSON.
  • Provisioned dashboard — A dashboard loaded from a file at Grafana start.
  • Runbook — A short page: what the alert means and the exact steps to fix it.
  • End-to-end test — Proving the whole path works by causing a real problem.
  • Resolve — The alert goes back to normal and a "resolved" message is sent.
  • Fill file — A big temporary file used only on a lab disk to test disk alerts.
  • Docker volume — Storage that survives container restarts.
Create the folder Write all files Start everything Check targets Open Grafana Run the alert test
Lab: app and host to Prometheus to Alertmanager to receiver, plus Grafana

How: step by step

  1. Create the folder

    mkdir -p ~/badgelab/{rules,grafana/provisioning/datasources,grafana/provisioning/dashboards,grafana/dashboards} && cd ~/badgelab
    

    What it does: All lab files here.

    Output

    (no output)
    
  2. Write all files

    Create the files from Examples 1 and 2
    

    What it does: Compose, configs, app, receiver.

    Output

    (no output)
    
  3. Start everything

    sudo docker compose up -d --build
    

    What it does: Builds the app and receiver, starts 6 containers.

    Output

    Container badgelab-prometheus-1  Started ... (6 containers)
    
  4. Check targets

    curl -s localhost:9090/api/v1/targets | grep -o '"health":"[a-z]*"'
    

    What it does: All up.

    Output

    "health":"up" (3 times)
    
  5. Open Grafana

    http://SERVER_IP:3000, Ops folder, Badge API
    

    What it does: The dashboard is already there.

    Output

    Badge API dashboard with 4 panels
    
  6. Run the alert test

    Example 3
    

    What it does: Fill, fire, clean, resolve.

    Output

    FIRING then RESOLVED in the receiver log
    

Example 1: The full lab stack: app, exporter, Prometheus, Alertmanager, receiver, Grafana

Stack. Docker Compose, Prometheus, Alertmanager, Grafana, Node Exporter

Goal. The full lab stack: app, exporter, Prometheus, Alertmanager, receiver, Grafana.

compose.yaml

services:
  badge-api:
    build: ./app
    ports: ["8000:8000"]
  node-exporter:
    image: prom/node-exporter:v1.8.2
    pid: host
    volumes: ["/:/host:ro,rslave"]
    command: ["--path.rootfs=/host"]
  prometheus:
    image: prom/prometheus:v2.54.1
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - ./rules:/etc/prometheus/rules:ro
    command: ["--config.file=/etc/prometheus/prometheus.yml", "--web.enable-lifecycle"]
    ports: ["9090:9090"]
  alertmanager:
    image: prom/alertmanager:v0.27.0
    volumes: ["./alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro"]
    ports: ["9093:9093"]
  receiver:
    build: ./receiver
  grafana:
    image: grafana/grafana:11.2.0
    environment: ["GF_SECURITY_ADMIN_PASSWORD=change-me-now"]
    volumes:
      - ./grafana/provisioning:/etc/grafana/provisioning:ro
      - ./grafana/dashboards:/var/lib/grafana/dashboards:ro
    ports: ["3000:3000"]

prometheus.yml

global: {scrape_interval: 15s, evaluation_interval: 15s}
rule_files: ["/etc/prometheus/rules/*.yml"]
alerting:
  alertmanagers: [{static_configs: [{targets: ["alertmanager:9093"]}]}]
scrape_configs:
  - job_name: badge-api
    static_configs: [{targets: ["badge-api:8000"]}]
  - job_name: node
    static_configs: [{targets: ["node-exporter:9100"]}]
  - job_name: prometheus
    static_configs: [{targets: ["localhost:9090"]}]

rules/disk.yml

groups:
  - name: badge-lab
    rules:
      - alert: DiskAlmostFull
        expr: 100 * (1 - node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) > 85
        for: 2m
        labels: {severity: warning, team: badge}
        annotations:
          summary: "Disk / is {{ printf \"%.0f\" $value }}% full on {{ $labels.instance }}"
          runbook: "Delete old files in /var/tmp, rotate logs, or grow the EBS volume"

alertmanager.yml

route:
  receiver: lab-webhook
  group_wait: 10s
  repeat_interval: 1h
receivers:
  - name: lab-webhook
    webhook_configs:
      - url: http://receiver:5001/alert
        send_resolved: true

What each line does

  • build: ./app — Builds our badge API image from the app folder (Example 2).
  • rules volume — Prometheus loads every rule file in the folder.
  • for: 2m — Short wait for the lab. Use 10m or more in real life.
  • webhook_configs url — Alertmanager posts JSON to our receiver container.
  • send_resolved: true — We also get a message when it is fixed.
  • GF_SECURITY_ADMIN_PASSWORD — Lab password only. Change it after first login.

Green output

$ sudo docker compose ps --format "{{.Service}} {{.Status}}"
alertmanager Up 30 seconds
badge-api Up 30 seconds
grafana Up 30 seconds
node-exporter Up 30 seconds
prometheus Up 30 seconds
receiver Up 30 seconds

Expected result. Six services running from one folder. This is a complete monitoring platform in miniature.

Example 2: The badge API, the webhook receiver and the provisioned dashboard

Stack. Python Flask, prometheus_client, Docker

Goal. The badge API, the webhook receiver and the provisioned dashboard.

app/app.py

from flask import Flask, Response
from prometheus_client import Counter, generate_latest
app = Flask(__name__)
BADGES = Counter("badges_issued_total", "Badges issued", ["kind"])

@app.route("/badge/<kind>")
def badge(kind):
    BADGES.labels(kind if kind in ("gold", "silver") else "other").inc()
    return {"badge": kind}

@app.route("/metrics")
def metrics():
    return Response(generate_latest(), mimetype="text/plain")

app.run(host="0.0.0.0", port=8000)

app/Dockerfile

FROM python:3.12-slim
RUN pip install --no-cache-dir flask prometheus-client
COPY app.py /app.py
CMD ["python", "/app.py"]

receiver/receiver.py

from flask import Flask, request
app = Flask(__name__)

@app.route("/alert", methods=["POST"])
def alert():
    body = request.get_json()
    for a in body["alerts"]:
        print(a["status"].upper(), a["labels"]["alertname"], "-", a["annotations"].get("summary", ""), flush=True)
    return "ok"

app.run(host="0.0.0.0", port=5001)

receiver/Dockerfile

FROM python:3.12-slim
RUN pip install --no-cache-dir flask
COPY receiver.py /receiver.py
CMD ["python", "/receiver.py"]

grafana/provisioning/datasources/prom.yml and dashboards/files.yml

# datasources/prom.yml
apiVersion: 1
datasources:
  - {name: Prometheus, type: prometheus, access: proxy, url: "http://prometheus:9090", isDefault: true}
# dashboards/files.yml
apiVersion: 1
providers:
  - {name: lab, folder: Ops, type: file, options: {path: /var/lib/grafana/dashboards}}

What each line does

  • @app.route("/badge/...") — A route with the badge kind in the URL.
  • kind if kind in ("gold", "silver") else "other" — Keeps label values small: only three possible values.
  • FROM python:3.12-slim — Small official Python image.
  • a["status"].upper() — FIRING or RESOLVED.
  • flush=True — Prints at once so docker logs shows it.
  • providers ... folder: Ops — Dashboards in grafana/dashboards appear in the Ops folder. Put host-overview.json from lesson 13.7 there, renamed to "Badge API".

Green output

$ for k in gold gold silver; do curl -s localhost:8000/badge/$k; done
{"badge":"gold"}{"badge":"gold"}{"badge":"silver"}
$ curl -s localhost:8000/metrics | grep ^badges
badges_issued_total{kind="gold"} 2.0
badges_issued_total{kind="silver"} 1.0

Expected result. The app reports business numbers. The receiver is ready to print alerts. Grafana loads the data source and dashboard by itself.

Example 3: The end-to-end alert test: fill, fire, clean, resolve, and the CloudWatch twin

Stack. Prometheus, Alertmanager webhook, CloudWatch alarm

Goal. The end-to-end alert test: fill, fire, clean, resolve, and the CloudWatch twin.

Run the test (lab VM only)

df -h /
# fill until above 85%. Adjust the size: (85% of Size) minus Used, plus 1G.
sudo fallocate -l 5G /var/tmp/fill.bin
df -h /
# watch the receiver log in a second terminal
sudo docker compose logs -f receiver
# after you see FIRING, clean up
sudo rm -f /var/tmp/fill.bin
df -h /

The same alarm on CloudWatch (uses the agent from lesson 13.3)

aws cloudwatch put-metric-alarm \
  --alarm-name badge-disk-almost-full \
  --namespace CWAgent --metric-name disk_used_percent \
  --dimensions Name=InstanceId,Value=i-0abc1234def567890 Name=path,Value=/ Name=device,Value=nvme0n1p1 Name=fstype,Value=xfs \
  --statistic Maximum --period 60 --evaluation-periods 2 \
  --threshold 85 --comparison-operator GreaterThanThreshold \
  --alarm-actions arn:aws:sns:ap-south-1:111122223333:ops-alerts

runbook.md

Alert: DiskAlmostFull (badge API host)
Means: root disk above 85% for 2+ minutes.
Check: df -h / ; sudo du -xh / --max-depth=2 | sort -h | tail -10
Fix:   delete old files in /var/tmp, run sudo journalctl --vacuum-size=200M,
       or grow the EBS volume and run sudo growpart + sudo resize2fs (or xfs_growfs).
Done when: df -h / shows below 80% and the alert says RESOLVED.
Owner: badge team on-call.

What each line does

  • fallocate -l 5G — Makes a big file instantly. Only on a lab disk.
  • docker compose logs -f receiver — Follows the receiver output live.
  • rm -f /var/tmp/fill.bin — Removes the fill file. Never forget this step.
  • CWAgent disk_used_percent — The agent metric. Dimensions must match exactly what list-metrics shows.
  • runbook.md — Five lines that let any teammate fix it alone.

Green output

Filesystem  Size  Used Avail Use% Mounted on
/dev/root    20G   12G  8.0G  60% /
/dev/root    20G   17G  3.0G  85% /    (wait, add 1G more if it shows exactly 85%)
receiver-1  | FIRING DiskAlmostFull - Disk / is 88% full on node-exporter:9100
/dev/root    20G   12G  8.0G  60% /
receiver-1  | RESOLVED DiskAlmostFull - Disk / is 88% full on node-exporter:9100

Expected result. You proved the full path: metric, rule, pending, firing, Alertmanager, receiver, cleanup, resolved. This is the proof the manager asked for.

Verify: did it work?

  1. Alerts API shows the state

    curl -s localhost:9090/api/v1/alerts | grep -o '"state":"[a-z]*"'
    

    What it does: During the test: pending then firing. After cleanup: nothing.

    Output

    "state":"firing"
    
  2. Alertmanager has it

    curl -s localhost:9093/api/v2/alerts | grep -o '"alertname":"[A-Za-z]*"'
    

    What it does: Alertmanager received the alert.

    Output

    "alertname":"DiskAlmostFull"
    

When it is red 1

receiver never prints anything

Cause. Alertmanager cannot reach the receiver, or Prometheus has no alerting section.

Fix, step by step

  1. curl -s localhost:9090/api/v1/alertmanagers must list alertmanager:9093.
  2. sudo docker compose logs alertmanager | grep -i error
  3. Check the webhook URL uses the service name receiver and port 5001.

When it is red 2

fallocate: fallocate failed: No space left on device

Cause. The fill size was bigger than the free space.

Fix, step by step

  1. Run df -h / again.
  2. Pick a size about 2 GB less than Avail.
  3. Never fill a production disk.

When it is red 3

Alert stays pending and never fires

Cause. The value dropped below 85 before 2 minutes, or the fill was too small.

Fix, step by step

  1. Run the expression in the Graph tab and read the value.
  2. Make the fill a bit bigger.
  3. Wait the full for: time.

Cleanup

  1. Remove the fill file (again, to be sure)

    sudo rm -f /var/tmp/fill.bin
    

    What it does: Frees the disk.

    Output

    (no output)
    
  2. Stop and delete the lab

    sudo docker compose down -v --rmi local
    

    What it does: Removes containers, volumes and the two built images.

    Output

    Container badgelab-grafana-1  Removed ... Image badgelab-badge-api  Removed
    
  3. Delete the CloudWatch alarm

    aws cloudwatch delete-alarms --alarm-names badge-disk-almost-full
    

    What it does: No charges after the lab.

    Output

    (no output)
    

Ravindra Bagale's Tip

Finish the lab: see the fire and also see the resolve. With that proof you can speak with confidence in an interview.

Practice tasks

Easy Screenshot proof

Why: Managers want proof, not words.

What to do: Take screenshots of the targets page, the dashboard and the FIRING line.

How:
  1. Save them in a folder with the date.

Check: Three screenshots show each stage.

Medium Business alert

Why: A badge API that issues zero badges is broken even if it is up.

What to do: Alert when increase(badges_issued_total[10m]) == 0 during day time.

How:
  1. Add the rule.
  2. Stop sending requests.
  3. Watch it fire.

Check: The receiver prints FIRING for the business alert.

Hard Move it to Kubernetes

Why: Real teams run this with kube-prometheus-stack.

What to do: Install kube-prometheus-stack with Helm on a kind cluster and import your rule as a PrometheusRule.

How:
  1. helm install mon oci://ghcr.io/prometheus-community/charts/kube-prometheus-stack
  2. kubectl apply -f your PrometheusRule YAML.

Check: Your DiskAlmostFull rule appears in the Prometheus UI in the cluster.

Easy Say the end-to-end monitoring lab in two lines

Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.

What to do: Write two short lines about the end-to-end monitoring lab for a fresher who knows only Linux, Git and Docker basics.

How:
  1. Write the problem it solves.
  2. Write the one command, query or config line you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Keep a throwaway monitoring lab

Why: Practice needs a lab you can break. If it gets messy, you delete the containers and start again in one minute.

What to do: Run Node Exporter in Docker and read its metrics page.

How:
  1. docker run -d --name ne -p 9100:9100 prom/node-exporter
  2. curl -s localhost:9100/metrics | grep node_load1
  3. docker rm -f ne

Check: You see a line that starts with node_load1 and a number.

Medium Do it on a second stack

Why: Monitoring ideas must work on Prometheus and on CloudWatch. Only the tool changes, not the thinking.

What to do: Repeat this lesson on a different stack than the one you used first.

How:
  1. If you used Prometheus, try the CloudWatch console or AWS CLI.
  2. Keep the same question: is it up, is it fast, is it failing, is it full?
  3. Compare the two graphs side by side.

Check: Both tools answer the same question with a number and a graph.

Medium Break it on purpose

Why: You must know the red error by face. During an outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using only the steps, without searching the web.

Medium Write a one-page runbook

Why: At 2 a.m. nobody remembers PromQL. A short page saves the on-call person.

What to do: Write a one-page runbook for this lesson.

How:
  1. Title, when the alert fires, the graph to open, the exact commands, how to check, how to undo.

Check: A teammate can follow it alone, without calling you.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the metric you watched, the number you saw and the fix.

Check: Your answer has a real metric name and a real number.

Hard Draw the flow top to bottom

Why: A drawing shows where a number is born and where it ends up.

What to do: Draw this lesson as boxes from top to bottom.

How:
  1. Start at the server or app, go through the exporter, Prometheus or CloudWatch, then Grafana, then the alert on your phone.

Check: Each box matches a real command or file in this lesson.

Homework: try at home

Try at home

At home, extend the lab: add a second alert "BadgeAPIDown" (up{job="badge-api"} == 0 for 1m), stop the badge-api container, and confirm the receiver prints FIRING and then RESOLVED when you start it again. Add it to your runbook.

Recap

  • You built a full monitoring stack from an empty folder.
  • The app and host send numbers; Prometheus stores and checks them.
  • Alertmanager sent FIRING and RESOLVED to a receiver.
  • You proved it end to end with a safe disk fill and cleanup.
  • The same alarm exists on CloudWatch for AWS teams.

FAQ

Can I run this lab on a laptop?

Yes, with Docker Desktop. Node Exporter will show the Docker VM disk, which is fine for practice.

How much RAM does the lab need?

About 1.5 GB. A t3.small is enough.

Why for: 2m in the lab but 10m in real life?

To save waiting time in practice. Real systems need longer windows to avoid noise.

Can I add Slack later?

Yes. Add a slack_configs receiver in alertmanager.yml next to the webhook.

What should I put on my resume?

"Built and tested Prometheus, Grafana and Alertmanager monitoring with end-to-end alert tests and runbooks."

Interview questions

  1. Walk me through a monitoring setup you built.

    Badge API with /metrics, Node Exporter, Prometheus with rules, Alertmanager routing to webhook or Slack, Grafana provisioned from Git; tested by filling a lab disk and seeing FIRING and RESOLVED.

  2. How do you test alerting end to end?

    Cause the real condition in a safe environment, watch pending and firing in Prometheus, confirm the notification, fix, confirm resolved; plus promtool unit tests.

  3. How would you move this to Kubernetes?

    kube-prometheus-stack via Helm, ServiceMonitors for apps, PrometheusRule objects for alerts, Grafana dashboards as ConfigMaps.

  4. Why keep both Prometheus and CloudWatch alarms?

    CloudWatch covers AWS managed services and still works if Prometheus is down; Prometheus covers apps and Kubernetes.

  5. What is in a good runbook?

    What the alert means, how to check, exact fix commands, how to confirm, and who owns it.

Quick quiz

Q1. Why use a webhook receiver in the lab?

To see alerts without any Slack or email account.

Q2. Which flag lets Alertmanager also send fixed alerts?

send_resolved: true.

Q3. Why limit the badge kind label to three values?

To keep cardinality small.

Q4. What must you always do after a disk fill test?

Delete the fill file.

Q5. What is a runbook?

A short page with the meaning of an alert and exact fix steps.

Lab

Build the primary monitoring path for a badge API lab host and prove one disk alert.

  1. Run Node Exporter; confirm /metrics responds on your chosen port.
  2. Run Prometheus with a scrape job for that exporter; confirm target UP.
  3. Run Grafana; add Prometheus data source; create a small dashboard (CPU, memory, disk %).
  4. Define one disk-used alert with a sustained duration.
  5. Trigger safely with a temporary fill file on a lab path; confirm alert fires.
  6. Delete the fill file; confirm alert resolves and disk recovers.
  7. Write a five-line runbook in your notes (not committed secrets).
  8. Optional: skim CloudWatch docs and write three bullets on how the same disk story would look there — no need to implement both.

Practice task

Explain golden signals to a project manager in six lines, mapping latency/traffic/errors/saturation to badge API peak traffic and a full disk.

Thodkyaat sangaycha tar

  • Monitor so you see trouble before customers do — bike dashboard before the highway stop.
  • Golden signals: latency, traffic, errors, saturation; host metrics explain saturation.
  • Primary path: Node Exporter → Prometheus → Grafana; CloudWatch is the AWS-native alternate (link AWS course for depth).
  • Prefer few clear panels and one trustworthy alert over noisy walls.
  • Trigger disk alerts safely on lab disks and always clean up; ports are published ports — do not expose admin UIs publicly without care.
  • No invented AWS prices or free-tier claims — stop idle labs.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards