Ravindra BagaleCourses & study guides मराठी

Chapter 13: Monitoring Basics

DevOps

13.7 Grafana — one calm dashboard

Why: the problem

It is 2 a.m. and the on-call engineer at Ola gets a call: "rides are failing". She has 30 seconds to understand the situation. If she opens Prometheus and starts typing queries, she loses ten minutes. If she opens one calm Grafana dashboard, she sees it at once: traffic normal, errors up from 0.1% to 8%, latency up, and database server CPU at 100%. A good dashboard is like the display in a hospital ICU. The doctor does not run tests at the bed. The screen already shows heart rate, oxygen and blood pressure, with red when something is wrong. Grafana lets you build that screen. But a bad dashboard with 60 random panels is as useless as no dashboard. That is why you learn to build one calm dashboard: golden signals on top, host metrics below, everything as code.

What we will build

You will connect Grafana to Prometheus by clicking and then as code (provisioning), so a new Grafana comes up ready. You will import the famous "Node Exporter Full" community dashboard. Then you will build your own small dashboard with a server dropdown variable and save it as JSON in Git. Finally you will add CloudWatch as a second data source, so one Grafana shows AWS and Prometheus together.

What: every term in plain English

  • Data source — Where Grafana reads data from: Prometheus, CloudWatch, MySQL, Loki and many more.
  • Panel — One graph or number box on a dashboard.
  • Dashboard — A page of panels.
  • Variable — A dropdown at the top, like "server", that changes all panels at once.
  • Provisioning — Grafana reads YAML and JSON files at start, so setup is code, not clicks.
  • Threshold colours — Green, orange, red levels on a panel, like disk above 80% shows orange.
  • Time range — The window you see, like "Last 6 hours".
  • Dashboard ID — A number on grafana.com to import a ready dashboard, like 1860.
Log in Add Prometheus by clicking Import a ready dashboard Make your own Export as JSON
Grafana: data source to queries to panels to dashboard

How: step by step

  1. Log in

    Browser: http://SERVER_IP:3000, user admin
    

    What it does: Use the password from compose.yaml and change it.

    Output

    Home - Grafana
    
  2. Add Prometheus by clicking

    Connections, Data sources, Add, Prometheus, URL http://prometheus:9090, Save and test
    

    What it does: Grafana talks to Prometheus over the Compose network.

    Output

    Successfully queried the Prometheus API.
    
  3. Import a ready dashboard

    Dashboards, New, Import, ID 1860, Load, choose Prometheus, Import
    

    What it does: Node Exporter Full, used by thousands of teams.

    Output

    Dashboard imported
    
  4. Make your own

    Dashboards, New, Add visualization
    

    What it does: Build the panels from Example 2.

    Output

    New dashboard
    
  5. Export as JSON

    Dashboard settings, JSON Model, copy
    

    What it does: Save it in Git so it is never lost.

    Output

    { "title": "Orders - host overview", ... }
    

Example 1: Data source and dashboards as code with provisioning

Stack. Grafana 11 provisioning, Docker Compose

Goal. Data source and dashboards as code with provisioning.

grafana/provisioning/datasources/prom.yml

apiVersion: 1
datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true
    jsonData:
      timeInterval: 15s

grafana/provisioning/dashboards/files.yml

apiVersion: 1
providers:
  - name: team-dashboards
    folder: Ops
    type: file
    options:
      path: /var/lib/grafana/dashboards

Add to the grafana service in compose.yaml

volumes:
  - grafana-data:/var/lib/grafana
  - ./grafana/provisioning:/etc/grafana/provisioning:ro
  - ./grafana/dashboards:/var/lib/grafana/dashboards:ro

What each line does

  • apiVersion: 1 — The provisioning file format version.
  • access: proxy — Grafana server calls Prometheus, not the browser.
  • url: http://prometheus:9090 — Service name from Compose.
  • isDefault: true — New panels use this data source.
  • timeInterval: 15s — Match the scrape interval so graphs are smooth.
  • folder: Ops — Dashboards from files appear in the Ops folder.
  • path: /var/lib/grafana/dashboards — Every .json file here becomes a dashboard.

Green output

$ mkdir -p grafana/provisioning/datasources grafana/provisioning/dashboards grafana/dashboards
$ sudo docker compose up -d grafana
$ sudo docker compose logs grafana | grep -i provision
logger=provisioning.datasources level=info msg="inserting datasource from configuration" name=Prometheus
logger=provisioning.dashboard level=info msg="starting to provision dashboards"

Expected result. A brand new Grafana now comes up with Prometheus already connected. No clicks. This is how teams at Razorpay and Freshworks keep Grafana repeatable.

Example 2: Your own dashboard JSON with a server dropdown

Stack. Grafana dashboard JSON

Goal. Your own dashboard JSON with a server dropdown.

grafana/dashboards/host-overview.json

{
  "title": "Orders - host overview",
  "uid": "orders-host",
  "time": { "from": "now-6h", "to": "now" },
  "refresh": "30s",
  "templating": { "list": [
    { "name": "server", "type": "query", "datasource": "Prometheus",
      "query": "label_values(node_load1, instance)", "includeAll": true, "multi": true }
  ]},
  "panels": [
    { "type": "stat", "title": "CPU busy %", "gridPos": {"x":0,"y":0,"w":8,"h":5},
      "targets": [{ "expr": "100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode=\"idle\",instance=~\"$server\"}[5m])))" }],
      "fieldConfig": { "defaults": { "unit": "percent", "thresholds": { "steps": [
        {"color":"green","value":null},{"color":"orange","value":70},{"color":"red","value":90}]}}}},
    { "type": "stat", "title": "Memory used %", "gridPos": {"x":8,"y":0,"w":8,"h":5},
      "targets": [{ "expr": "100 * (1 - node_memory_MemAvailable_bytes{instance=~\"$server\"} / node_memory_MemTotal_bytes{instance=~\"$server\"})" }],
      "fieldConfig": { "defaults": { "unit": "percent" }}},
    { "type": "gauge", "title": "Disk used % (/)", "gridPos": {"x":16,"y":0,"w":8,"h":5},
      "targets": [{ "expr": "100 * (1 - node_filesystem_avail_bytes{mountpoint=\"/\",instance=~\"$server\"} / node_filesystem_size_bytes{mountpoint=\"/\",instance=~\"$server\"})" }],
      "fieldConfig": { "defaults": { "unit": "percent", "max": 100 }}},
    { "type": "timeseries", "title": "Load (1m)", "gridPos": {"x":0,"y":5,"w":24,"h":8},
      "targets": [{ "expr": "node_load1{instance=~\"$server\"}", "legendFormat": "{{instance}}" }]}
  ]
}

What each line does

  • "uid": "orders-host" — A fixed id, so links to the dashboard never break.
  • "refresh": "30s" — The page updates itself every 30 seconds.
  • label_values(node_load1, instance) — Fills the dropdown with every server name.
  • instance=~"$server" — Each query uses the chosen servers.
  • thresholds steps — Green normally, orange at 70, red at 90.
  • gridPos — Place and size on a 24-column grid. Three boxes on top, one wide graph below.
  • legendFormat "{{instance}}" — Shows the server name on each line.

Green output

$ sudo docker compose restart grafana
Grafana, Dashboards, Ops folder:
  Orders - host overview
Top row: CPU busy % 34 (green)  Memory used % 62  Disk used % 82 (orange)
Dropdown "server": All, 10.0.1.12:9100, 10.0.1.13:9100, 10.0.2.40:9100

Expected result. One calm dashboard: three numbers and one graph. Pick a server in the dropdown and every panel changes.

Example 3: Add CloudWatch to the same Grafana

Stack. Grafana, Amazon CloudWatch, IAM role

Goal. Add CloudWatch to the same Grafana.

grafana/provisioning/datasources/cloudwatch.yml

apiVersion: 1
datasources:
  - name: CloudWatch
    type: cloudwatch
    jsonData:
      authType: default
      defaultRegion: ap-south-1

Panel query (in the panel editor)

Data source : CloudWatch
Namespace   : AWS/ApplicationELB
Metric name : HTTPCode_Target_5XX_Count
Statistic   : Sum
Dimensions  : LoadBalancer = app/orders-alb/50dc6c495c0c9188
Period      : 1m

What each line does

  • type: cloudwatch — The built-in CloudWatch plugin.
  • authType: default — Use the IAM role of the EC2 where Grafana runs. No keys in files.
  • defaultRegion: ap-south-1 — Mumbai region.
  • AWS/ApplicationELB — The load balancer metric group.
  • HTTPCode_Target_5XX_Count — How many 5xx errors your app servers returned.

Green output

Save and test: Successfully queried the CloudWatch metrics API.
Panel "ALB 5xx per minute": 0, 0, 1, 0, 14, 22, 3, 0

Expected result. Now one dashboard can show the ALB errors from CloudWatch next to host CPU from Prometheus. The role needs the CloudWatchReadOnlyAccess policy.

Verify: did it work?

  1. Data sources loaded?

    curl -s -u admin:YOUR_PASS localhost:3000/api/datasources | python3 -m json.tool | grep name
    

    What it does: Lists the data sources.

    Output

    "name": "Prometheus",
    "name": "CloudWatch",
    
  2. Grafana healthy?

    curl -s localhost:3000/api/health
    

    What it does: Database must be ok.

    Output

    {"database": "ok", "version": "11.2.0"}
    

When it is red 1

Post "http://localhost:9090/api/v1/query": dial tcp 127.0.0.1:9090: connect: connection refused

Cause. Inside the Grafana container, localhost means Grafana itself, not Prometheus.

Fix, step by step

  1. Change the URL to http://prometheus:9090 (the Compose service name).
  2. Save and test again.
  3. If Prometheus is on another server, use its private IP.

When it is red 2

Panel shows "No data"

Cause. The query is wrong, the time range has no data, or the variable has no match.

Fix, step by step

  1. Click the panel, Edit, and open Query inspector.
  2. Run the same query in Prometheus.
  3. Check the $server variable and widen the time range.

When it is red 3

Dashboard title cannot be saved: provisioned dashboard

Cause. Dashboards from files are read only in the UI.

Fix, step by step

  1. Edit the JSON file in Git instead.
  2. Or Save as a copy for experiments.
  3. Restart Grafana or wait for the provider to reload.

Cleanup

  1. Delete test dashboards

    rm grafana/dashboards/host-overview.json && sudo docker compose restart grafana
    

    What it does: Removes the dashboard.

    Output

    (no output)
    
  2. Stop Grafana

    sudo docker compose stop grafana
    

    What it does: Stops the container, keeps data.

    Output

    Container monstack-grafana-1  Stopped
    

Ravindra Bagale's Tip

A dashboard should be as calm as an ICU screen. Not 60 panels — 6 good panels are enough.

Practice tasks

Easy Add a Text panel

Why: Dashboards need a short "what to do" note for on-call.

What to do: Add a text panel with the runbook link and owner team.

How:
  1. Add visualization, Text.
  2. Write two lines.

Check: The note shows on top.

Medium Network panel

Why: Network spikes explain many slow incidents.

What to do: Add a timeseries panel for network in and out in Mbps.

How:
  1. Use rate(node_network_receive_bytes_total[5m]) * 8 / 1e6.
  2. Set unit to Mbps.

Check: You see in and out lines per server.

Hard Dashboard per service from one template

Why: Big teams have 50 services and one dashboard template.

What to do: Add a "job" variable and make all queries use job=~"$job".

How:
  1. label_values(up, job)
  2. Replace fixed job names.

Check: One dashboard works for every service.

Easy Say Grafana dashboards 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 Grafana dashboards 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, import dashboard 1860 and dashboard 3662 (Prometheus 2.0 overview) on your lab. Then delete everything you do not understand from 1860 and keep only six panels. Small dashboards are better dashboards.

Recap

  • Grafana turns Prometheus and CloudWatch numbers into dashboards.
  • Keep it calm: golden signals on top, host metrics below.
  • Use variables so one dashboard serves many servers.
  • Provision data sources and dashboards from files in Git.
  • Inside Docker, call Prometheus by service name, not localhost.

FAQ

Is Grafana a database?

No. It only reads from data sources and draws.

Can Grafana send alerts?

Yes, Grafana alerting can, but many teams keep alerts in Prometheus with Alertmanager.

How many panels should a dashboard have?

Fewer than 12 for an on-call dashboard. Make separate deep-dive dashboards.

Can I use Grafana with MySQL?

Yes, MySQL is a data source; useful for business numbers like orders per hour.

Grafana Cloud or self-hosted?

Cloud for small teams with no ops time; self-hosted when you need full control.

Interview questions

  1. How do you manage Grafana dashboards in a team?

    Store dashboard JSON and data source YAML in Git and load them with provisioning or Terraform; review changes with pull requests.

  2. What makes a good dashboard?

    Answers one question fast, golden signals first, consistent units and colours, few panels, links to runbooks.

  3. What are Grafana variables?

    Template variables like $server filled by queries such as label_values, used to reuse one dashboard for many targets.

  4. How does Grafana read CloudWatch without keys?

    It uses the IAM role of the EC2 or the pod (IRSA) via the default credential chain.

  5. Why "No data" on a panel?

    Wrong query, wrong data source, empty time range, or variable mismatch; check with Query inspector.

Quick quiz

Q1. Default Grafana port?

3000.

Q2. What is a dashboard variable?

A dropdown that changes queries on all panels.

Q3. Why use provisioning?

Setup is code, repeatable and in Git.

Q4. Why does localhost:9090 fail inside Grafana container?

localhost is the Grafana container itself.

Q5. Which ID is Node Exporter Full?

1860.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards