Kubernetes Field Guide · Chapter 14 of 16
Observability: Prometheus, Grafana and alerts
A deploy is only done when you can see it working. Learn what to measure, how Prometheus collects it, how to query it, and how to alert so that a page means a real problem, without letting the monitoring bill outgrow the thing it monitors.
- 40 min
- Advanced
- Hands-on
- Free
By Joshua Sequeira, founding engineer running Kubernetes in production. Updated .
By the end you can
0 of 5
Live lab in this chapter
A real-feeling terminal and a live cluster map, right in your browser. Every command block below has a ▶ Run in lab button.
Metrics, logs and traces
| Signal | Answers | Typical tools |
|---|---|---|
| Metrics | Is something wrong, and how much? Cheap numbers over time. | Prometheus, CloudWatch metrics |
| Logs | What exactly happened in this request or this crash? | Loki, CloudWatch Logs, Elasticsearch |
| Traces | Where did the time go across services? | OpenTelemetry with Tempo or Jaeger |
For every user-facing service, start with the four golden signals: latency (how long requests take, as p95 or p99, not averages), traffic (requests per second), errors (the share that fail) and saturation (how full the most constrained resource is).
Prometheus and PromQL
Prometheus pulls metrics: every 15–30 seconds it scrapes an HTTP /metrics endpoint on each target and stores the numbers as time series. In Kubernetes it gets three kinds of data:
- Your apps, which expose metrics through a client library, discovered with a
ServiceMonitor. - kube-state-metrics: the state of objects (desired vs available replicas, restarts, pod phases).
- The kubelet and node-exporter: container and node CPU, memory, disk and network.
| Question | PromQL |
|---|---|
| Requests per second | sum(rate(http_requests_total[5m])) |
| Error ratio | sum(rate(http_requests_total{code=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) |
| p95 latency | histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))) |
| CPU used vs requested, per pod | sum by (pod) (rate(container_cpu_usage_seconds_total[5m])) |
| Pods restarting | increase(kube_pod_container_status_restarts_total[15m]) > 3 |
Dashboards
Grafana turns queries into dashboards. Make one per service with the golden signals at the top, then saturation and dependencies below. A good dashboard answers "is it us, and since when?" in ten seconds. Mark deploys on it, because the most common cause of an incident is the last change.
Alerts that matter
Every page should be real, urgent and actionable. If people learn that alerts are usually noise, they stop reading them, and then miss the real one. Tune this alert until it pages once:
Interactive
Tune an alert: p95 latency, last 60 minutes
As a Prometheus rule, with the for duration that filtered the blips:
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: shop-api
labels:
release: kps
spec:
groups:
- name: shop-api
rules:
- alert: ShopApiHighLatency
expr: |
histogram_quantile(0.95,
sum by (le) (rate(http_request_duration_seconds_bucket{service="shop-api"}[5m]))
) > 0.5
for: 5m
labels:
severity: page
annotations:
summary: "shop-api p95 latency above 500ms for 5 minutes"
runbook: "https://wiki.example.com/runbooks/shop-api-latency"- The kube-prometheus-stack only loads rules carrying its release label by default.
- Must stay true for 5 minutes before it fires.
- Alertmanager routes by labels: page someone, or post to a channel.
- Every paging alert links to what to do.
Step through it
From a slow request to a message in Slack
- App/metrics
- Prometheusscrape + rules
- Alertmanagerroute, group
- Slack#alerts
- On callyou
Step 0 of 6
Press Play, or step through with Next.
The cost of observability
Monitoring can quietly become one of the largest lines on a cloud bill. The usual causes:
- Cardinality. Every distinct set of label values is a separate time series. A label with user IDs, request IDs or full URLs creates millions. Keep labels bounded; put per-request detail in logs or traces.
- Log volume. Managed log services bill per GB ingested and stored. Debug logging left on in production, and logging every health check, cost real money. Set retention per log group instead of keeping everything forever.
- Retention. Keep high-resolution metrics for days or weeks; downsample or drop after that.
- Traces. Sample: keep every error and slow trace, and a small percentage of the rest.
Cardinality is the one that surprises people, because it multiplies. Add labels to one ordinary metric:
Interactive · Cost
One metric, http_requests_total. How many series?
Hands-on: install the stack
The lab is docked at the bottom of your screen.
Live lab · no install
Install the monitoring stack
- Tasks0/7
Start with what kubectl already shows
Usage per pod, before any dashboards.
kubectl top pods kubectl top nodesRead logs from every replica at once
kubectl logs -l app=web --prefix --tail=3Install the monitoring stack
Prometheus, Alertmanager, Grafana, kube-state-metrics and node-exporter in one chart.
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts helm install kps prometheus-community/kube-prometheus-stack -n monitoring --create-namespace --wait kubectl -n monitoring get podsGet the Grafana password
kubectl -n monitoring get secret kps-grafana -o jsonpath="{.data.admin-password}" | base64 -dOpen Grafana and Prometheus
On your laptop these open in a browser at localhost:3000 and localhost:9090.
kubectl -n monitoring port-forward svc/kps-grafana 3000:80 & kubectl -n monitoring port-forward svc/prometheus-operated 9090 &Break something and find it from events
Events are the first signal, before any metric moves.
kubectl set image deployment/web nginx=nginx:1.27-typo sleep 5 kubectl get events --field-selector type=Warning | tail -n 5Recover
kubectl rollout undo deployment/web kubectl rollout status deployment/web- Lab complete. Keep experimenting, or press Reset to start again.
- ready
- starting / not ready
- failing
- terminating
Prefer your own machine? The same steps on a local cluster
The kube-prometheus-stack chart installs Prometheus, Alertmanager, Grafana, kube-state-metrics, node-exporter and a set of ready-made dashboards and alerts. Back on the kind cluster:
kubectl config use-context kind-learn
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install kps prometheus-community/kube-prometheus-stack -n monitoring --create-namespace --wait
kubectl -n monitoring get pods
kps- Short release name. Resource names start with it, such as kps-grafana.
--wait- Takes a few minutes the first time while images download.
kubectl -n monitoring get secret kps-grafana -o jsonpath="{.data.admin-password}" | base64 -d; echo
kubectl -n monitoring port-forward svc/kps-grafana 3000:80 &
kubectl -n monitoring port-forward svc/prometheus-operated 9090 &
admin-password- Log in to Grafana at http://localhost:3000 as admin with this password.
prometheus-operated- Prometheus UI at http://localhost:9090. Try the queries from the table above.
In Grafana, open Dashboards → Kubernetes / Compute Resources / Namespace (Pods) and pick default: CPU and memory per pod, against requests and limits.
Mini mission
Find your waste
In Prometheus, write one query that shows, for each pod in default, its CPU usage divided by its CPU request. Which pods would you right-size, and in which direction?
Reveal one safe solution
sum by (pod) (rate(container_cpu_usage_seconds_total{namespace="default", container!=""}[5m]))
/
sum by (pod) (kube_pod_container_resource_requests{namespace="default", resource="cpu"})Values far below 1 are over-requested: lower their requests and fit more on each node (chapter 9). Values above 1 are using more than they reserved and are first in line when the node gets busy: raise their requests. Look at a week of data before changing production numbers, not five minutes.
Check yourself
Quiz
0 of 4 answered