Ravindra BagaleCourses & study guides मराठी

Chapter 13: Monitoring Basics

DevOps

13.1 Why monitor — dashboard before the outage call

Why: the problem

Think of Swiggy on a Friday night at 8 p.m. Lakhs of people open the app at the same time. One small server runs out of disk space at 7:40 p.m. Nobody notices. At 8:05 p.m. orders start failing. Customers post angry tweets. The support team calls the DevOps engineer. She opens her laptop and asks: what broke, and when did it start? If the team had monitoring, a graph would show disk going up from 70% to 100% over twenty minutes. An alert would have reached her phone at 7:45 p.m., before any customer saw an error. Without monitoring she starts guessing: is it the database, the network, the code? Monitoring is like the dashboard of a bike. The speed, fuel and engine temperature are always in front of you. You see the fuel light before the bike stops on the highway. In the same way, a server dashboard shows CPU, memory, disk and errors all the time. That is why every DevOps engineer must know how to collect numbers, draw them and get one calm alert at the right time.

What we will build

You will build a tiny "health watcher" in three steps. First, a plain Bash script that prints CPU load, memory and disk on any Linux server. Second, a small Python web app with a /health page, plus a loop that checks it every five seconds and shouts when it fails. Third, you will read the same kind of numbers from AWS CloudWatch with one AWS CLI command. You will see that every monitoring tool, small or big, does the same three jobs: collect a number, keep it with a time, and warn you when it crosses a line.

What: every term in plain English

  • Monitoring — Collecting numbers about a system again and again, and watching them over time.
  • Metric — One number with a name and a time, like disk_used_percent = 82 at 9:00 p.m.
  • Dashboard — A screen with graphs of the metrics, like the speedometer of a bike.
  • Alert — A message (Slack, email, phone call) sent when a metric crosses a line for some time.
  • Threshold — The line that is not okay, like "disk used more than 85%".
  • Health check — A small URL like /health that says "I am fine" with HTTP 200.
  • Outage — Time when users cannot use the app.
  • MTTD — Mean time to detect. How fast you notice a problem. Monitoring makes it small.
Make a lab folder Check the load average Check memory Check disk Run the pulse script from Example 1 Run the health watcher from Example 2
Why monitor: server to number to graph to alert

How: step by step

  1. Make a lab folder

    mkdir -p ~/monlab && cd ~/monlab
    

    What it does: All files for this chapter live here.

    Output

    (no output)
    
  2. Check the load average

    uptime
    

    What it does: Shows how busy the CPU has been in the last 1, 5 and 15 minutes.

    Output

    21:00:01 up 3 days,  2:11,  1 user,  load average: 0.42, 0.35, 0.30
    
  3. Check memory

    free -m
    

    What it does: Shows total, used and available RAM in MB.

    Output

                   total        used        free      shared  buff/cache   available
    Mem:            3910        1210         820          12        1880        2440
    
  4. Check disk

    df -h /
    

    What it does: Shows how full the root disk is.

    Output

    Filesystem      Size  Used Avail Use% Mounted on
    /dev/xvda1       20G   14G  6.0G  70% /
    
  5. Run the pulse script from Example 1

    bash pulse.sh
    

    What it does: Prints all three numbers in one line, with time.

    Output

    2026-10-25T21:00:05 load=0.42 mem_used=31% disk_used=70%
    
  6. Run the health watcher from Example 2

    python3 watch.py
    

    What it does: Checks the app every 5 seconds and prints OK or DOWN.

    Output

    21:00:10 OK 200 in 12 ms
    

Example 1: A Bash pulse script that prints load, memory and disk in one line

Stack. Ubuntu 24.04 or Amazon Linux 2023, Bash

Goal. A Bash pulse script that prints load, memory and disk in one line.

pulse.sh

#!/usr/bin/env bash
# Prints one line of health numbers. Safe to run anywhere.
ts=$(date +%Y-%m-%dT%H:%M:%S)
load=$(cut -d " " -f1 /proc/loadavg)
mem=$(free | awk '/Mem:/ {printf "%d", $3*100/$2}')
disk=$(df / --output=pcent | tail -1 | tr -d " %")
echo "$ts load=$load mem_used=${mem}% disk_used=${disk}%"
if [ "$disk" -ge 85 ]; then
  echo "$ts WARN disk is above 85 percent" 1>&2
fi

What each line does

  • cut -d " " -f1 /proc/loadavg — Takes the 1-minute load number from the kernel.
  • free | awk ... — Divides used memory by total memory and prints a percent.
  • df / --output=pcent — Prints only the "Use%" column for the root disk.
  • tr -d " %" — Removes spaces and the % sign, so we get a plain number.
  • [ "$disk" -ge 85 ] — Checks if disk is 85 or more. -ge means greater or equal.
  • 1>&2 — Sends the warning to stderr, so it stands out from normal lines.

Green output

$ bash pulse.sh
2026-10-25T21:00:05 load=0.42 mem_used=31% disk_used=70%
$ watch -n 5 bash pulse.sh
Every 5.0s: bash pulse.sh
2026-10-25T21:00:10 load=0.44 mem_used=31% disk_used=70%

Expected result. You get one clear line. With watch -n 5 it repeats every five seconds. This is monitoring in its smallest form.

Example 2: A Python app with a /health page and a watcher loop that alerts when it fails

Stack. Python 3, Flask

Goal. A Python app with a /health page and a watcher loop that alerts when it fails.

app.py

from flask import Flask
import shutil

app = Flask(__name__)

@app.route("/health")
def health():
    total, used, free = shutil.disk_usage("/")
    pct = used * 100 // total
    if pct >= 95:
        return {"status": "down", "disk_used": pct}, 503
    return {"status": "ok", "disk_used": pct}, 200

@app.route("/")
def home():
    return "Orders app is running"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

watch.py

import time, urllib.request

URL = "http://localhost:5000/health"
fails = 0
while True:
    t0 = time.time()
    try:
        code = urllib.request.urlopen(URL, timeout=2).status
    except Exception:
        code = 0
    ms = int((time.time() - t0) * 1000)
    now = time.strftime("%H:%M:%S")
    if code == 200:
        fails = 0
        print(now, "OK", code, "in", ms, "ms")
    else:
        fails += 1
        print(now, "DOWN", code, "fail count", fails)
        if fails == 3:
            print(now, "ALERT: health failed 3 times in a row")
    time.sleep(5)

What each line does

  • shutil.disk_usage("/") — Reads total, used and free bytes of the root disk.
  • return {...}, 503 — 503 means "service unavailable". Load balancers stop sending traffic.
  • urlopen(URL, timeout=2) — Calls /health. If it takes more than 2 seconds, we treat it as failed.
  • code = 0 — No answer at all, for example the app is stopped.
  • if fails == 3 — Alert only after 3 failures in a row. One blip is not an outage.
  • time.sleep(5) — Check every 5 seconds. This is the "scrape interval" idea.

Green output

$ python3 app.py &
 * Running on http://0.0.0.0:5000
$ python3 watch.py
21:00:10 OK 200 in 12 ms
21:00:15 OK 200 in 9 ms
(now stop the app with: pkill -f app.py)
21:00:20 DOWN 0 fail count 1
21:00:25 DOWN 0 fail count 2
21:00:30 DOWN 0 fail count 3
21:00:30 ALERT: health failed 3 times in a row

Expected result. The watcher noticed the app was down within 15 seconds and raised one alert, not ten. Real tools like Prometheus and Uptime Kuma do the same, only bigger.

Example 3: Read real CPU numbers from AWS CloudWatch with the AWS CLI

Stack. AWS EC2, CloudWatch, AWS CLI v2

Goal. Read real CPU numbers from AWS CloudWatch with the AWS CLI.

Commands

aws cloudwatch get-metric-statistics \
  --namespace AWS/EC2 \
  --metric-name CPUUtilization \
  --dimensions Name=InstanceId,Value=i-0abc1234def567890 \
  --start-time 2026-10-25T14:00:00Z \
  --end-time 2026-10-25T15:00:00Z \
  --period 300 \
  --statistics Average Maximum \
  --output table

What each line does

  • --namespace AWS/EC2 — The group of metrics. EC2 sends CPU, network and disk IO here for free.
  • --metric-name CPUUtilization — The CPU busy percent of the instance.
  • --dimensions Name=InstanceId,... — Which server. Use your own instance id.
  • --start-time / --end-time — The time window, in UTC (the Z at the end).
  • --period 300 — One data point every 300 seconds (5 minutes).
  • --statistics Average Maximum — For each 5 minutes, give the average and the highest value.

Green output

------------------------------------------------
|            GetMetricStatistics               |
+----------------------------------------------+
||                 Datapoints                 ||
|+----------+-----------+----------------------+|
|| Average  |  Maximum  |  Timestamp           ||
|+----------+-----------+----------------------+|
||  12.4    |  18.0     |  2026-10-25T14:00:00Z||
||  13.1    |  21.5     |  2026-10-25T14:05:00Z||
||  71.8    |  96.2     |  2026-10-25T14:10:00Z||
|+----------+-----------+----------------------+|

Expected result. You can see a CPU spike at 14:10 UTC (7:40 p.m. IST). CloudWatch kept the numbers for you even when you were not looking.

Verify: did it work?

  1. Check the app is healthy

    curl -s -w " %{http_code}\n" localhost:5000/health
    

    What it does: Prints the JSON body and the status code.

    Output

    {"disk_used":70,"status":"ok"} 200
    
  2. Check the watcher sees it

    python3 watch.py
    

    What it does: The first line must be OK.

    Output

    21:01:00 OK 200 in 10 ms
    

When it is red 1

bash: free: command not found

Cause. Very small images like Alpine or BusyBox do not have the procps package.

Fix, step by step

  1. On Alpine run: apk add procps
  2. On Ubuntu run: sudo apt-get install -y procps
  3. Run bash pulse.sh again.

When it is red 2

urllib.error.URLError: [Errno 111] Connection refused

Cause. The app is not running or listens on a different port.

Fix, step by step

  1. Check: ss -ltnp | grep 5000
  2. Start the app: python3 app.py
  3. Make sure URL in watch.py uses the same port.

When it is red 3

An error occurred (AccessDenied) when calling the GetMetricStatistics operation

Cause. Your IAM user or role has no cloudwatch:GetMetricStatistics permission.

Fix, step by step

  1. Ask the admin to attach the CloudWatchReadOnlyAccess policy.
  2. Or run the command from an EC2 role that has it.
  3. Run aws sts get-caller-identity to see who you are.

Cleanup

  1. Stop the lab apps

    pkill -f app.py ; pkill -f watch.py
    

    What it does: Stops the Flask app and the watcher.

    Output

    (no output)
    
  2. Remove the folder if you want

    rm -rf ~/monlab/__pycache__
    

    What it does: Removes Python cache files only.

    Output

    (no output)
    

Ravindra Bagale's Tip

Monitoring is the bike dashboard. When the fuel needle drops, fill petrol early — do not wait to break down on the highway.

Practice tasks

Easy Add a CPU check to /health

Why: A server can be up but too busy to serve.

What to do: Make /health return 503 when the 1-minute load is above the CPU count.

How:
  1. Read os.getloadavg()[0].
  2. Compare with os.cpu_count().
  3. Return 503 if load is higher.

Check: Under load, /health shows status down.

Medium Send the alert to Slack

Why: A print on a screen is not an alert if nobody is looking.

What to do: Post the ALERT line to a Slack incoming webhook.

How:
  1. Create a test Slack channel and webhook.
  2. Use urllib.request with a JSON body {"text": "..."}.
  3. Keep the webhook URL in an environment variable, never in code.

Check: A message appears in the Slack channel when the app is down.

Hard Find your own outage on CloudWatch

Why: Real practice is reading real graphs.

What to do: On a test EC2 run a CPU burn for 5 minutes and find it in CloudWatch.

How:
  1. sudo apt-get install -y stress-ng
  2. stress-ng --cpu 2 --timeout 300
  3. Run the get-metric-statistics command from Example 3.

Check: You see one 5-minute period with a high Maximum value.

Easy Say monitoring 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 monitoring 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, change pulse.sh to also print the number of running processes (ps -e --no-headers | wc -l). Then run it with watch -n 5 for one minute while you open a big app on your laptop. Note how load and processes change.

Recap

  • Monitoring is the bike dashboard of your servers.
  • A metric is a number with a name and a time.
  • Even a Bash script can collect load, memory and disk.
  • A good alert fires only after a problem lasts, not on one blip.
  • CloudWatch keeps EC2 numbers for you on AWS; Prometheus does it anywhere.

FAQ

Is monitoring the same as logging?

No. Monitoring gives numbers over time. Logs give the story of one event. You need both.

Do I need Prometheus for a small project?

No. Start with a health URL and a simple checker. Use Prometheus when you have many servers.

How often should I check?

Every 15 to 60 seconds is normal. Every 1 second costs a lot and helps little.

Is CloudWatch free?

Basic EC2 metrics every 5 minutes are free. Detailed 1-minute metrics and custom metrics cost money.

Who looks at dashboards?

The DevOps or SRE team, the on-call engineer and often the developers of that service.

What is the first thing to monitor?

Is the app up, and is the disk not full. These two cause many outages.

Interview questions

  1. Why do we need monitoring?

    To detect problems before users do, to see trends like a disk filling up, and to find the root cause faster during an incident.

  2. What is the difference between monitoring and observability?

    Monitoring watches known numbers with alerts. Observability means you can ask new questions using metrics, logs and traces together.

  3. What is a health check endpoint?

    A URL like /health that returns 200 when the app is fine and 503 when it is not. Load balancers and Kubernetes use it.

  4. How do you avoid false alerts?

    Alert only when a condition lasts for some time, for example 3 checks or 5 minutes, and alert on what users feel.

  5. Tell me one real monitoring win.

    Example: a disk-full alert at 85% fired 30 minutes before a log partition filled; we rotated logs and there was no outage.

Quick quiz

Q1. What is a metric?

One number with a name and a time, like CPU 40% at 9 p.m.

Q2. Why alert only after 3 failures?

One short failure can be a network blip. Three in a row is a real problem.

Q3. Which HTTP code says "not ready"?

503 Service Unavailable.

Q4. Which AWS service keeps EC2 CPU numbers?

Amazon CloudWatch.

Q5. What does monitoring reduce?

The time to detect a problem (MTTD), so users see fewer errors.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards