---
title: "Kubernetes Monitoring with Prometheus and Grafana: Metrics, Dashboards, and Alerts"
description: "You'll learn what Prometheus actually scrapes and why nothing pushes to it, the four exporters that cover a cluster, how one careless label turns 600 time series into 120 million, and which alerts are worth waking someone up for."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/devtips/post/kubernetes-monitoring-prometheus-grafana-dashboards
---

# Kubernetes Monitoring with Prometheus and Grafana: Metrics, Dashboards, and Alerts

Every cluster reaches the same moment. Something is slow, three people have `kubectl` open, and everyone is running `top` on a different pod. Somebody eventually says "we should have monitoring", and a week later there are eighteen Grafana dashboards that nobody opens because none of them answer the question anyone actually has.

This is about building the version that gets opened. What to collect, what to ignore, and which alerts earn the right to wake someone up.

## What Prometheus actually does

### It pulls, and everything follows from that

Prometheus asks the Kubernetes API what exists, then makes an HTTP request to each target on a fixed interval and stores what comes back. Your application does not send metrics anywhere. It exposes a `/metrics` endpoint and waits to be asked.

Two consequences are worth holding onto, because they explain most of the behaviour people find surprising.

A workload that exists between two scrapes is never observed. With a 30 second interval, a pod that starts and finishes in 40 seconds might be scraped once, or not at all. This is not a defect, it is what pull means, and it is the one situation where Pushgateway is the right answer rather than a workaround.

And a target that goes away does not announce it. It simply stops responding, which Prometheus records as `up == 0` for that target. That single metric is the most useful alert in the system and the one most often left unconfigured.

_From service discovery to a dashboard, and where AWS takes over_

### The four things worth scraping

A cluster needs four sources, and each answers a question the others cannot.

`node-exporter` runs as a DaemonSet and reports on the machine: CPU, memory, disk, filesystem, network. It answers "is the hardware in trouble".

`kube-state-metrics` reads the Kubernetes API and turns object state into metrics. It answers "does reality match what I declared". This is the one teams skip, and it is the one that tells you a Deployment wants three replicas and has one, or that a pod has restarted forty times in an hour. Nothing else in the stack knows that.

cAdvisor is already inside the kubelet, so there is nothing to install. It reports per-container CPU and memory, which is what you need to size requests and limits honestly.

Then your own application, which is the only source that knows whether the business is working. Everything above can look perfect while checkout returns a 500 to every customer.

`node-exporter` and `kube-state-metrics` sound similar and overlap in nothing. One is about machines, the other is about Kubernetes objects. Running only the first is the most common gap I see, and it is why a cluster can look healthy on every graph while a Deployment has been stuck for a day.

## The problem with getting this wrong

### Cardinality is arithmetic, and it is unforgiving

Prometheus stores one time series per unique combination of label values. Not one per metric. That distinction is the whole game.

_How one label turns 600 time series into 120 million_

The failure mode is what makes this dangerous. Cardinality does not degrade gradually and give you time to react. Memory climbs quietly for a week, then the Prometheus pod is OOMKilled, and unless you configured a PersistentVolume, the entire history goes with it. The first time most teams learn this is during the incident where they most needed the history.

### The real-world consequences

Two more failures worth naming, because both are quiet.

Prometheus with no persistent storage keeps everything in a pod's ephemeral filesystem. A node drain, a rescheduled pod, a helm upgrade, and every graph starts at "now". You discover this while trying to compare today's latency against last Tuesday's.

And the dashboard problem. Importing a community dashboard by ID takes ten seconds and gives you sixty panels, of which four are relevant to your workload. Nobody deletes the other fifty-six, so during an incident people scroll past a wall of graphs looking for the one that matters. A dashboard with six panels that someone chose deliberately beats a dashboard with sixty that someone imported.

## Collect the four sources, label carefully, alert on symptoms

### Getting it running

The `kube-prometheus-stack` chart installs Prometheus, Grafana, Alertmanager, `node-exporter` and `kube-state-metrics` together, wired up and with the CRDs in place. Installing them individually is possible and there is no reason to.

```bash
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update

helm install monitoring prometheus-community/kube-prometheus-stack \
  --namespace monitoring --create-namespace \
  --values values.yaml
```

The values that matter are the ones the defaults get wrong for a real cluster:

```yaml title="values.yaml" showLineNumbers
prometheus:
  prometheusSpec:
    retention: 30d
    retentionSize: 45GB # keep this below the volume size

    # Without this block, metrics live in the pod's ephemeral
    # filesystem and vanish on every reschedule.
    storageSpec:
      volumeClaimTemplate:
        spec:
          storageClassName: gp3
          accessModes: ['ReadWriteOnce']
          resources:
            requests:
              storage: 50Gi

    resources:
      requests:
        memory: 4Gi
        cpu: 500m
      limits:
        memory: 8Gi # no CPU limit: throttling a scraper causes gaps

    # By default the operator only picks up ServiceMonitors it
    # created. These two lines let application teams add their own.
    serviceMonitorSelectorNilUsesHelmValues: false
    podMonitorSelectorNilUsesHelmValues: false

grafana:
  adminPassword: '' # leave empty and set it from a Secret
  persistence:
    enabled: true
    size: 5Gi
  sidecar:
    dashboards:
      enabled: true # dashboards from ConfigMaps, so they live in git

alertmanager:
  alertmanagerSpec:
    storage:
      volumeClaimTemplate:
        spec:
          storageClassName: gp3
          accessModes: ['ReadWriteOnce']
          resources:
            requests:
              storage: 5Gi
```

`retentionSize` deserves a moment. Prometheus deletes old blocks when either limit is hit, and if the size limit is set above the actual volume capacity, the volume fills first and Prometheus stops accepting writes. Leave headroom.

### Exposing metrics from your own service

The client library does the work. Four metrics cover most services:

```typescript title="metrics.ts" showLineNumbers

// Process-level metrics: heap, event loop lag, GC, open handles.
collectDefaultMetrics({register: registry});

  name: 'http_requests_total',
  help: 'Total HTTP requests',
  // Every label here has a small, fixed set of values.
  // Nothing that grows with traffic belongs in this list.
  labelNames: ['method', 'status', 'route'],
  registers: [registry],
});

  name: 'http_request_duration_seconds',
  help: 'HTTP request duration',
  labelNames: ['method', 'route'],
  // Buckets are cumulative and each one is its own series.
  // Choose them around the latency you care about, not evenly.
  buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
  registers: [registry],
});
```

The `route` label has to be the route template, not the path. `/users/:id` is one label value; `/users/8814` is one label value per user, which is the cardinality problem arriving through the front door. Most frameworks expose the matched route, and using the raw URL instead is the most common way this mistake ships.

Then the endpoint, and the `ServiceMonitor` that tells Prometheus to scrape it:

```typescript title="server.ts" showLineNumbers
app.get('/metrics', async (_req, res) => {
  res.set('Content-Type', registry.contentType);
  res.end(await registry.metrics());
});
```

```yaml title="servicemonitor.yaml" showLineNumbers
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: checkout-api
  namespace: production
  labels:
    release: monitoring # must match the Prometheus serviceMonitorSelector
spec:
  selector:
    matchLabels:
      app: checkout-api # selects the Service, not the Pod
  endpoints:
    - port: http # the NAME of the port in the Service, not the number
      path: /metrics
      interval: 30s
```

Two fields cause nearly all the "my ServiceMonitor is ignored" reports. `port` is the port's name in the Service and silently matches nothing if you write a number. And the `release` label has to match what the Prometheus resource selects, which is why the chart values above turn the restrictive default off.

Check `Status > Targets` in the Prometheus UI before assuming anything works. A target that is discovered but failing shows the exact HTTP error, and a target that is missing entirely means the selector never matched. That page answers the question faster than reading YAML.

### The dashboards worth having

Start with three, and let anything else earn its place.

A cluster overview: node CPU and memory against allocatable, pod count per node, and pods not in `Running`. This answers "is the platform healthy".

A per-service view driven by a template variable: request rate, error rate, and latency percentiles for whichever service is selected. One dashboard serves every service, which is what stops the dashboard list from growing to sixty.

And a capacity view: requested versus actual CPU and memory per namespace. This is the one that finds the deployment asking for 2 CPUs and using 0.05, which is usually the cheapest performance work available.

The queries behind them are short:

```promql
# Request rate per second, by route
sum(rate(http_requests_total[5m])) by (route)

# Error rate as a percentage of all requests
sum(rate(http_requests_total{status=~"5.."}[5m]))
  / sum(rate(http_requests_total[5m])) * 100

# p99 latency. histogram_quantile needs the _bucket series and le.
histogram_quantile(0.99,
  sum(rate(http_request_duration_seconds_bucket[5m])) by (le, route))

# Pods restarting: the signal is the rate, not the total
sum(rate(kube_pod_container_status_restarts_total[15m])) by (namespace, pod)

# Requested CPU that is not being used, by namespace
sum(kube_pod_container_resource_requests{resource="cpu"}) by (namespace)
  - sum(rate(container_cpu_usage_seconds_total[5m])) by (namespace)
```

`rate()` needs a range at least four times the scrape interval to survive a missed scrape. With 30 second scrapes, `[5m]` has enough slack. `[1m]` produces gaps in the graph the first time a scrape fails, and people then blame the application.

### Alerts that are worth a phone call

One rule has served me better than any other. Page on symptoms, not causes. High CPU is not an incident. High CPU while every request still returns in 40 milliseconds is a machine doing its job.

```yaml title="alerts.yaml" showLineNumbers
groups:
  - name: symptoms
    rules:
      - alert: HighErrorRate
        expr: |
          sum(rate(http_requests_total{status=~"5.."}[5m])) by (service)
            / sum(rate(http_requests_total[5m])) by (service) > 0.05
        for: 5m # 'for' is what separates an alert from a blip
        labels:
          severity: page
        annotations:
          summary: '{{ $labels.service }} is returning 5xx for {{ $value | humanizePercentage }} of requests'

      - alert: TargetDown
        expr: up == 0
        for: 10m
        labels:
          severity: page
        annotations:
          summary: '{{ $labels.job }} has not been scrapeable for 10 minutes'

      - alert: PodCrashLooping
        expr: rate(kube_pod_container_status_restarts_total[15m]) > 0
        for: 15m
        labels:
          severity: ticket
        annotations:
          summary: '{{ $labels.namespace }}/{{ $labels.pod }} is restarting repeatedly'

      - alert: PersistentVolumeFillingUp
        expr: |
          kubelet_volume_stats_available_bytes
            / kubelet_volume_stats_capacity_bytes < 0.10
        for: 30m
        labels:
          severity: page
        annotations:
          summary: 'PVC {{ $labels.persistentvolumeclaim }} is above 90% full'
```

`for` is what separates an alert from noise. Without it, one slow scrape fires the page. With `for: 5m`, the condition has to hold continuously, which filters out almost everything that would have resolved itself.

The other discipline is deletion. If an alert has never once been the reason somebody found a real problem, remove it. Its only remaining function is to train people to ignore alerts, and that training transfers to the alerts that matter.

## Quick implementation steps

1. Install `kube-prometheus-stack` into a `monitoring` namespace, with `storageSpec` set. Skipping the volume is the decision you regret during the first incident.
2. Confirm `node-exporter` and `kube-state-metrics` are both scraping in `Status > Targets`. Two sources, two different questions.
3. Add a `/metrics` endpoint to one service and a `ServiceMonitor` for it. Verify it appears as a target before writing any dashboard.
4. Audit your labels before the second service. Anything that grows with traffic (user, session, request, trace, full URL) does not belong in a metric.
5. Build the three dashboards: cluster overview, per-service with a template variable, capacity by namespace. Resist importing more.
6. Write four alerts on symptoms, all with a `for` clause. Route `severity: page` to a pager and `severity: ticket` to a queue.
7. Add a panel for `prometheus_tsdb_head_series` and alert on its slope. This is the smoke detector for cardinality.

### On AWS specifically

Amazon Managed Service for Prometheus changes the ownership rather than the architecture. You still run a Prometheus in the cluster, but in agent mode. It scrapes and forwards over `remote_write`, and stores nothing locally. Retention, scaling and the PersistentVolume stop being yours.

What changes is where a mistake shows up. Self-hosted, a cardinality explosion is an OOMKilled pod. Managed, it is an invoice, because you pay per ingested sample and per query. The failure is gentler and considerably more expensive, and it is worth telling the team which of those two failure modes they are now living with.

Managed Grafana is a smaller decision. It handles SSO through IAM Identity Center, which is worth real money if you have been maintaining Grafana users by hand, and it costs per active user per month. If your Grafana already authenticates against your identity provider, self-hosting it is fine.

## Benefits of getting this right

You stop guessing. "The API got slower around 14:00" becomes a graph with a timestamp, and the deploy that caused it is visible on the same axis.

Capacity planning turns into arithmetic. Requested versus actual usage per namespace usually reveals that half the cluster is reserved for workloads that never touch it, and rightsizing requests is the least glamorous cost reduction available.

Incidents get shorter, for a specific reason. Everyone looks at the same dashboard instead of three people running `top` on three different pods and reporting three different stories.

And on-call gets quieter, which is the one that keeps engineers. Alerts on symptoms with a `for` clause fire rarely and mean something when they do.

## What's your approach?

### Community discussion

The thing I would most like to hear about is where people draw the line between metrics and traces. My rule is that a metric answers how many, how fast, how often, and anything that answers "what happened to this specific request" belongs in a trace or a log. It is a clean line in theory and I still see it crossed regularly, usually by someone who just wanted one more label to help with debugging.

### Share your experience

If you have run into a cardinality explosion, I would like to know which label did it. In my experience it is almost never the obvious one that somebody argued about in review. It is a small addition made in a hurry during an incident, to make debugging easier, that nobody removed afterwards.
