# Grafana dashboards

Connect Grafana to Prometheus, build a dashboard people actually read, make it reusable with variables, and keep it in Git with provisioning so it survives a rebuild.

Course: [Monitoring](https://devops.rajeev.pro/courses/monitoring), lesson 3. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/monitoring/03-grafana-dashboards

## What you will learn

- Explain what Grafana stores and what it doesn't
- Add a Prometheus data source, by hand and from a provisioning file
- Build panels with the right visualisation, unit and thresholds for each question
- Add a variable so one dashboard works for every server
- Provision dashboards from JSON files kept in Git

## Why dashboards need their own tool

Prometheus answers any question you can type. Grafana is what makes the answers usable by a whole
team, at 2 a.m., in seconds.

### Before: queries typed from memory

You have Prometheus and PromQL. An incident starts at 2 a.m. You open the Prometheus UI and type
queries from memory, one per tab: CPU, memory, error rate. The latency query you can't quite
remember.

> **Figure.** Animated. At 02:07 an engineer types PromQL queries into separate tabs one after another: CPU, memory, 5xx errors. The fourth tab, a latency query, is half remembered. One graph per tab, one query at a time, all from memory.
>
> Every incident started by rebuilding the same graphs.

### The problem: the knowledge lives in one head

Your new teammate doesn't know the queries. The product manager asks "is the site healthy?" and
gets a screenshot of a PromQL expression. Nobody can see traffic, errors, latency and saturation
side by side, for any server.

> **Figure.** Animated. You know the queries. A new teammate asks which query shows errors. A manager asks whether the site is healthy and receives a screenshot of a PromQL expression.
>
> The queries lived in one person's head.

### The fix: saved panels on one dashboard

Grafana saves each query once as a **panel** and arranges panels on a **dashboard**. One link shows
the whole picture, for any server and any time range, to anyone on the team.

> **Figure.** Animated. A dashboard called Node overview fills in panel by panel: CPU used 31.5 percent, memory used 34.9 percent, root disk 9.90 percent, load per core 0.365, then a CPU-by-mode graph and a network graph.
>
> Queries saved once as panels, shown together.

### How it works: every panel asks again

Grafana stores no metrics. When you open a dashboard or change a dropdown, every panel sends its
saved query to a **data source**, such as Prometheus, for the chosen time range, and draws what comes
back.

> **Figure.** Animated. The Server dropdown changes from All to web-2. Four panel queries travel from Grafana to Prometheus, which returns only web-2 series, and the panels redraw.
>
> Grafana stores dashboards, not metrics.

In this lesson you'll connect Grafana to Prometheus, build the dashboard below, make it work for
any server, and keep it in Git so a lost Grafana is rebuilt in minutes.

> **Figure.** A Grafana dashboard called Node overview with a Server dropdown set to All and a 30 minute time range. Top row: CPU used 31.5 percent, memory used 34.9 percent, a gauge showing root disk 9.90 percent used, and load per core 0.365. Bottom row: a time series of CPU time by mode, with system and user between 200 and 600 milliseconds per second, and a time series of network bytes received on eth0, around 47 bytes per second.
>
> The dashboard you build in this lesson, with real data from the lab machine. Four stat panels answer 'right now', two graphs answer 'over time'.

## Data sources

A **data source** is a connection Grafana uses to fetch data: a type (Prometheus, Loki, Jaeger,
PostgreSQL, CloudWatch), a URL and, if needed, credentials. You set it up once, and every panel
picks it by name.

Start Grafana next to Prometheus on the same Docker network as lesson 2:

```sh
$ docker run -d --name grafana --network mon -p 3000:3000 grafana/grafana
$ curl -s localhost:3000/api/health
{
  "database": "ok",
  "version": "13.3.0",
  "commit": "6f8ce3c693b493043ebcd4787566d2b6b118b0f0"
}
```

Log in at `http://localhost:3000` (first login `admin` / `admin`, then it asks for a new password).
Go to **Connections → Data sources → Add data source → Prometheus**, set the URL to
`http://prometheus:9090` and press **Save & test**.

Two details trip people up:

- The URL is resolved **by the Grafana server**, not by your browser. Inside Docker, that's
  `http://prometheus:9090`. `localhost:9090` would point at the Grafana container itself.
- **Access: Server (proxy)** is the default and the right choice. The browser asks Grafana, and
  Grafana asks Prometheus, so Prometheus never has to be reachable from users' laptops.

### Provision the data source from a file

Clicking works once. For a server you can rebuild, describe the data source in a file that
Grafana reads at startup:

```yaml
# provisioning/datasources/prometheus.yml
apiVersion: 1
datasources:
  - name: Prometheus
    type: prometheus
    uid: prometheus # a fixed id dashboards can refer to
    access: proxy
    url: http://prometheus:9090
    isDefault: true
```

Mount the folder at `/etc/grafana/provisioning` and the API confirms it, marked read-only because
the file owns it:

```sh
$ curl -s -u admin:admin localhost:3000/api/datasources
[
    {
        "uid": "prometheus",
        "name": "Prometheus",
        "type": "prometheus",
        "access": "proxy",
        "url": "http://prometheus:9090",
        "isDefault": true,
        "readOnly": true,
        ...
    }
]
```

(The real answer has a few more fields, cut here with `...`.)

## Build a dashboard

A **dashboard** is a page of **panels**. A panel is one question: a query, a visualisation, a unit
and optional thresholds. Create one with **Dashboards → New → New dashboard → Add visualization**.

> **Figure.** Data sources on the left: Prometheus with PromQL, Loki with LogQL, Jaeger or Tempo with trace IDs. In the middle, a panel called CPU used with its query, visualisation time series, unit percent, thresholds 70 amber and 90 red, and a legend of instance. On the right, a dashboard stored as JSON with a variable called instance whose values come from label_values of up by instance, and four panels: traffic, errors, latency p95 and saturation.
>
> A panel is a saved query plus how to draw it. A dashboard is a JSON file of panels and variables.

### Pick the visualisation from the question

| Question                     | Visualisation     | Example from the dashboard    |
| ---------------------------- | ----------------- | ----------------------------- |
| What is it right now?        | Stat              | CPU used 31.5%                |
| How close is it to a limit?  | Gauge             | Root disk 9.90% used          |
| How did it change over time? | Time series       | CPU by mode, network received |
| Which ones are worst?        | Bar gauge / table | Top 5 servers by memory       |

### Set the unit and thresholds

Every panel query from lesson 2 works as-is. For "CPU used":

```promql
100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle", instance=~"$instance"}[5m])))
```

In the panel options set **Unit → Percent (0-100)** and **Thresholds → 70 orange, 90 red**. Units
matter more than they look: without one, 974034223104 is a mystery; with **bytes(SI)** Grafana
shows 974 GB. Thresholds turn a number into a judgement a tired person can read in one second.

### A real mistake: the panel that said "No data"

The first version of the "Load (1m) per core" panel showed **No data**, while the other five panels
worked. The query was:

```promql
node_load1{instance=~"$instance"} / count by (instance) (node_cpu_seconds_total{mode="idle", instance=~"$instance"})
```

It's the label-matching problem from lesson 2: `node_load1` carries `job` and `env`, the right side
only `instance`, so the division matched nothing. Adding `on (instance)` after the `/` fixed it,
and the panel showed 0.365. When a single panel is empty, copy its query into **Explore** (the
compass icon) and run it there. Grafana only draws what the data source returns.

### Lay it out for the reader

- **Top row: the answer.** Four stat panels a manager can read: is it healthy?
- **Below: the detail.** Time series an engineer uses to find out why.
- **One topic per dashboard.** "Node overview" for servers, "Checkout service" for an app. A
  50-panel dashboard is one nobody reads.
- **Name panels as questions or plain nouns** ("CPU used", "Errors per second"), never a PromQL
  expression.

## Variables

Without variables, you'd copy the dashboard for every server and fix forty copies every time a
panel changes. A **variable** is a dropdown at the top of the dashboard whose value is pasted into
every query.

Create one in **Dashboard settings → Variables → New variable**:

| Setting     | Value                                     | Why                                   |
| ----------- | ----------------------------------------- | ------------------------------------- |
| Name        | `instance`                                | Used in queries as `$instance`        |
| Type        | Query                                     | Values come from the data source      |
| Query       | `label_values(node_uname_info, instance)` | Every instance that has node_exporter |
| Multi-value | on, with **Include All**                  | Pick one server, several, or all      |
| Refresh     | On time range change                      | New servers appear without a reload   |

Then filter every panel query with `instance=~"$instance"`. Use `=~` (regex match), not `=`:
when you pick several servers or **All**, Grafana fills the variable with a regex like
`(web-1|web-2)`, and `=` would match nothing.

What happens when someone picks a server:

1. Grafana replaces `$instance` in every panel's query with the chosen value.
2. Each panel sends its query to Prometheus for the current time range.
3. Prometheus returns only that server's series, and the panels redraw.

Other useful variables: `$job` for the service, `$env` for staging or production, and the built-in
`$__rate_interval`, which picks a safe `rate()` window for the current zoom level. Grafana's docs
recommend `rate(x[$__rate_interval])` instead of a fixed `[5m]` in dashboards.

> **Video.** [Server Monitoring // Prometheus and Grafana Tutorial](https://www.youtube.com/watch?v=9TJx7QTrTyo) (Christian Lempa)

## Keep dashboards in Git

A dashboard is a **JSON document**. Open **Edit → Settings → JSON Model** (or **Export → Export as
JSON**) and you'll see every panel, query and variable. That means it can live in Git, be reviewed
in a pull request, and be loaded automatically.

Tell Grafana where the files are with a dashboard provider:

```yaml
# provisioning/dashboards/provider.yml
apiVersion: 1
providers:
  - name: from-git
    folder: Servers # the folder they appear in
    type: file
    options:
      path: /var/lib/grafana/dashboards # mount your JSON files here
```

The lab's `node-overview.json` (a fixed `uid` of `node-overview`, six panels, one variable) was
mounted at that path, and Grafana loaded it at startup into the **Servers** folder:

```sh
$ curl -s -u admin:admin "localhost:3000/api/search?query=node"
[
    {
        "uid": "node-overview",
        "title": "Node overview",
        "url": "/d/node-overview/node-overview",
        "type": "dash-db",
        "folderTitle": "Servers",
        ...
    }
]
```

Grafana checks the folder every 10 seconds by default. When the load-panel fix above was saved to
the JSON file, the dashboard updated without a restart.

> **Start from a community dashboard.** grafana.com/grafana/dashboards has thousands of ready dashboards. "Node Exporter Full" (ID 1860) is the classic one for node_exporter. Import it by ID, learn from its queries, then build a smaller one your team will actually read.

> **In production.** Provision data sources and dashboards from Git and treat hand-made changes as drafts. Put Grafana behind your company login (OAuth or SAML), give most people the Viewer role, and change the default `admin` password on day one. Grafana's own database (SQLite by default) holds users and settings: use PostgreSQL or MySQL if several Grafana servers share it.

## Mission: Build and provision a node dashboard

Build a dashboard called 'Node overview' with an instance variable and at least four panels: CPU used, memory used, root disk used and load per core, each with a unit and thresholds. Export it as JSON, delete it from Grafana, then bring it back through a dashboard provider and confirm it with the search API.

- You need: Prometheus and node_exporter from lesson 2
- You'll have: node-overview.json in a provisioning folder

```sh
$ mkdir -p provisioning/datasources provisioning/dashboards dashboards
$ # save prometheus.yml and provider.yml from this lesson, and your exported JSON as dashboards/node-overview.json
$ docker rm -f grafana
$ docker run -d --name grafana --network mon -p 3000:3000 \
    -v $PWD/provisioning:/etc/grafana/provisioning:ro \
    -v $PWD/dashboards:/var/lib/grafana/dashboards:ro grafana/grafana
$ curl -s -u admin:admin "localhost:3000/api/search?query=node"
```

The search answer should list "Node overview" in the "Servers" folder. Change the server dropdown
and check every panel follows. If one panel says "No data", run its query in Explore and look for
a label mismatch.

## Try it

- Run Grafana and open `http://localhost:3000/api/health`; note the version it reports.
- Add Prometheus as a data source and press "Save & test".
- Build a stat panel for CPU used, in percent, with thresholds at 70 and 90.
- Add a `$instance` variable from `label_values(node_uname_info, instance)` and use it in a query.
- Export the dashboard as JSON, delete it, and bring it back with a provisioning file.
- Do the mini mission and keep `node-overview.json`.

## Quiz

1. Where does Grafana keep the CPU numbers you see on a dashboard?
   - In Grafana's own database
   - **Nowhere; each panel queries the data source, such as Prometheus, when it loads** (answer)
   - In the browser's local storage
   Why: Grafana stores dashboards, users and settings, not metrics. Each panel is a saved query that runs against its data source for the chosen time range.

2. A panel shows "No data", but the same query works in the Prometheus UI. What should you check first?
   - **The panel's data source, time range and the variable values it uses** (answer)
   - The Grafana version
   - The panel's colour scheme
   Why: The usual causes are the wrong data source, a time range with no data, or a variable that filters out every series. Open the panel's query and look at what it actually sent.

3. Why use a `$instance` variable instead of one dashboard per server?
   - Variables make queries faster
   - **One dashboard serves every server; choosing a value in the dropdown re-runs every panel for it** (answer)
   - Grafana allows only one dashboard per data source
   Why: The variable's values come from a query such as label_values(node_uname_info, instance). Panels use instance=~"$instance", so a new server appears in the dropdown with no dashboard edits.

4. What is the main benefit of provisioning dashboards from files?
   - They load faster in the browser
   - **Dashboards live in Git, get reviewed like code, and come back automatically on a new Grafana** (answer)
   - Provisioned dashboards don't need a data source
   Why: A file provider loads JSON dashboards from a folder at startup and keeps them in sync. Losing the Grafana server no longer means losing every dashboard someone built by hand.

5. Which visualisation fits "how full is the root disk right now"?
   - **A gauge or stat panel with thresholds** (answer)
   - A time series with ten lines
   - A table of every sample
   Why: A single current value with a limit is a gauge or stat. Time series fit questions about change over time, like CPU by mode over the last hour.

## Resources

- [Grafana documentation](https://grafana.com/docs/grafana/latest/) (Grafana Labs)
- [Configure the Prometheus data source](https://grafana.com/docs/grafana/latest/datasources/prometheus/configure/) (Grafana Labs)
- [Provision Grafana (data sources and dashboards)](https://grafana.com/docs/grafana/latest/administration/provisioning/) (Grafana Labs)
- [Dashboard variables](https://grafana.com/docs/grafana/latest/dashboards/variables/) (Grafana Labs)
- [Dashboard best practices](https://grafana.com/docs/grafana/latest/dashboards/build-dashboards/best-practices/) (Grafana Labs)
- [Run Grafana in Docker](https://grafana.com/docs/grafana/latest/setup-grafana/installation/docker/) (Grafana Labs)
