Day 10: Prometheus, alerts, Grafana
Goal: The platform monitors itself and its teams: install kube-prometheus-stack, make the kubeadm control plane measurable, collect metrics from a team application, write a recording rule and an alerting rule, route alerts to the team, deliver a dashboard as code and let Argo Rollouts decide based on Prometheus · Duration: approx. 90 min · Prerequisite: Day 9
Briefing
- kube-prometheus-stack bundles what a platform needs for measuring: the Prometheus Operator, Prometheus, Alertmanager, Grafana, node-exporter (nodes) and kube-state-metrics (state of the Kubernetes objects) – plus ready-made rules and dashboards.
- The operator turns monitoring into Kubernetes objects that teams create in their own namespace:
| Object | Meaning |
|---|---|
| ServiceMonitor / PodMonitor | “Collect metrics from these pods” |
| PrometheusRule | Recording and alerting rules |
| AlertmanagerConfig | Where alerts with certain labels go |
- Recording rules precompute expensive queries and
store them as a new time series. Naming scheme:
level:metric:operation, e.g.namespace_job:http_fehlerquote:rate1m. - An alert has three states: inactive →
pending (condition met,
foris running) → firing (sent to Alertmanager).
Drill 1: Installation
# on cp1
mkdir -p ~/cnpe/tag10 && cd ~/cnpe/tag10
cat > monitoring-werte.yaml <<'EOF'
prometheus:
service:
type: NodePort
nodePort: 30090
prometheusSpec:
priorityClassName: plattform-kritisch
retention: 3d # keep data for 3 days
serviceMonitorSelectorNilUsesHelmValues: false # collect ServiceMonitors from all namespaces,
podMonitorSelectorNilUsesHelmValues: false # not only those with the Helm release's label
ruleSelectorNilUsesHelmValues: false # the same for rules
resources:
requests: {cpu: 200m, memory: 1Gi}
limits: {memory: 2Gi}
grafana:
adminPassword: grafana-lab-123
service:
type: NodePort
nodePort: 30030
alertmanager:
service:
type: NodePort
nodePort: 30093
EOF
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
# the namespace may already exist (Challenge from Day 1) – create it if not
k create namespace monitoring --dry-run=client -o yaml | k apply -f -
helm install monitoring prometheus-community/kube-prometheus-stack --version 94.2.0 -n monitoring -f monitoring-werte.yaml
k -n monitoring rollout status deploy/monitoring-grafana --timeout=400s
k -n monitoring wait --for=condition=Ready pod -l app.kubernetes.io/name=prometheus --timeout=400s
k -n monitoring get podsExpected (abridged):
STATUS: deployed
deployment "monitoring-grafana" successfully rolled out
pod/prometheus-monitoring-kube-prometheus-prometheus-0 condition met
NAME READY STATUS RESTARTS AGE
alertmanager-monitoring-kube-prometheus-alertmanager-0 2/2 Running 0 2m41s
monitoring-grafana-5d5f66d9b7-5gmbw 3/3 Running 0 2m58s
monitoring-kube-prometheus-operator-6b77dd6c5b-w7cv5 1/1 Running 0 2m58s
monitoring-kube-state-metrics-7d94c4cbd8-p5njl 1/1 Running 0 2m58s
monitoring-prometheus-node-exporter-4cb8s 1/1 Running 0 2m58s
monitoring-prometheus-node-exporter-hfc54 1/1 Running 0 2m58s
monitoring-prometheus-node-exporter-k82m2 1/1 Running 0 2m58s
prometheus-monitoring-kube-prometheus-prometheus-0 2/2 Running 0 2m40s
UIs: Prometheus http://172.16.0.126:30090, Alertmanager
:30093, Grafana :30030 (user
admin, password from the values).
Save your progress? Sign up for free
Drill 2: Making the control plane measurable
# on cp1
sleep 60
# all scrape targets with their state, via the Prometheus HTTP API
curl -s 'http://172.16.0.126:30090/api/v1/targets?state=active' \
| jq -r '.data.activeTargets[] | "\(.labels.job) \(.health)"' | sort | uniq -cExpected:
1 apiserver up
2 coredns up
1 kube-controller-manager down
1 kube-etcd down
3 kube-proxy down
1 kube-scheduler down
1 kube-state-metrics up
9 kubelet up
...
3 node-exporter up
kubeadm has etcd, the scheduler, the controller manager and
kube-proxy offer their metrics only on 127.0.0.1.
Prometheus runs in a pod and cannot reach them – after 15 minutes,
alerts such as KubeSchedulerDown fire. In the exam, a
typical “monitoring reports the control plane as down”.
# on cp1
# back up the static pod manifests – NOT to /etc/kubernetes/manifests (kubelet would start them)
mkdir -p ~/cnpe/tag10/sicherung
sudo cp /etc/kubernetes/manifests/{etcd,kube-controller-manager,kube-scheduler}.yaml ~/cnpe/tag10/sicherung/
# etcd: metrics on all addresses (port 2381, metrics only, no data)
sudo sed -i 's#--listen-metrics-urls=http://127.0.0.1:2381#--listen-metrics-urls=http://0.0.0.0:2381#' \
/etc/kubernetes/manifests/etcd.yaml
# scheduler and controller manager: HTTPS port with authentication on all addresses
sudo sed -i 's#--bind-address=127.0.0.1#--bind-address=0.0.0.0#' \
/etc/kubernetes/manifests/kube-controller-manager.yaml /etc/kubernetes/manifests/kube-scheduler.yaml
# kubelet notices the change and restarts the pods
sleep 60
k -n kube-system get pods -l tier=control-plane
# kube-proxy: the setting lives in a ConfigMap
k -n kube-system get cm kube-proxy -o yaml \
| sed 's/metricsBindAddress: ""/metricsBindAddress: 0.0.0.0:10249/' | k apply -f -
k -n kube-system rollout restart ds/kube-proxy
k -n kube-system rollout status ds/kube-proxy --timeout=120s
sleep 60
curl -s 'http://172.16.0.126:30090/api/v1/targets?state=active' \
| jq -r '.data.activeTargets[] | "\(.labels.job) \(.health)"' | sort | uniq -c | grep -E 'kube-(controller|etcd|proxy|scheduler)'Expected (abridged):
NAME READY STATUS RESTARTS AGE
etcd-cp1 1/1 Running 1 110m
kube-apiserver-cp1 1/1 Running 0 110m
kube-controller-manager-cp1 1/1 Running 0 110m
kube-scheduler-cp1 1/1 Running 0 110m
configmap/kube-proxy configured
daemonset.apps/kube-proxy restarted
daemon set "kube-proxy" successfully rolled out
1 kube-controller-manager up
1 kube-etcd up
3 kube-proxy up
1 kube-scheduler up
The backup does not belong in /etc/kubernetes/manifests:
the kubelet starts every YAML file there as a static pod – two etcd pods
with the same database are an emergency.
Save your progress? Sign up for free
Drill 3: A team’s metrics
podinfo is a small web application that, among other
things, counts http_requests_total by status code under
/metrics. Team Blue delivers it with a ServiceMonitor:
# on cp1
cat > podinfo.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: podinfo
namespace: team-blue
spec:
replicas: 2
selector:
matchLabels: {app: podinfo}
template:
metadata:
labels: {app: podinfo}
spec:
containers:
- name: podinfo
image: ghcr.io/stefanprodan/podinfo:6.11.0
ports: [{name: http, containerPort: 9898}]
resources:
requests: {cpu: 50m, memory: 64Mi}
limits: {cpu: 200m, memory: 128Mi}
---
apiVersion: v1
kind: Service
metadata:
name: podinfo
namespace: team-blue
labels: {app: podinfo} # the ServiceMonitor looks for this
spec:
selector: {app: podinfo}
ports: [{name: http, port: 9898}] # named port – the ServiceMonitor refers to it
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: podinfo
namespace: team-blue
spec:
selector:
matchLabels: {app: podinfo} # which Services
endpoints:
- port: http # name of the Service port
path: /metrics
interval: 15s
EOF
k apply -f podinfo.yaml
k -n team-blue rollout status deploy/podinfo --timeout=120s
sleep 45
curl -s 'http://172.16.0.126:30090/api/v1/targets?state=active' \
| jq -r '.data.activeTargets[] | select(.labels.job=="podinfo") | "\(.labels.pod) \(.health) \(.lastError)"'Expected:
podinfo-57ddf96bf8-tfhks down Get "http://10.244.1.203:9898/metrics": context deadline exceeded
podinfo-57ddf96bf8-2k5x8 down Get "http://10.244.2.156:9898/metrics": context deadline exceeded
Prometheus finds the pods but cannot reach them: the NetworkPolicy
allow-monitoring from Day 1 allows the
monitoring namespace only port 80. Add the port:
# on cp1
# JSON patch: append a port to the list (/- = at the end)
k -n team-blue patch netpol allow-monitoring --type=json \
-p '[{"op":"add","path":"/spec/ingress/0/ports/-","value":{"port":9898,"protocol":"TCP"}}]'
sleep 40
curl -s 'http://172.16.0.126:30090/api/v1/targets?state=active' \
| jq -r '.data.activeTargets[] | select(.labels.job=="podinfo") | "\(.labels.pod) \(.health)"'Expected:
networkpolicy.networking.k8s.io/allow-monitoring patched
podinfo-57ddf96bf8-tfhks up
podinfo-57ddf96bf8-2k5x8 up
Now traffic – good and failing requests (/status/500
deliberately responds with 500):
# on cp1
k -n team-blue run last --image=busybox:1.37 --restart=Never -- /bin/sh -c \
'while true; do wget -q -O- http://podinfo:9898/ >/dev/null; wget -q -O- http://podinfo:9898/status/500 >/dev/null 2>&1; sleep 0.2; done'
sleep 60
# requests per second by status – PromQL via the API
curl -s http://172.16.0.126:30090/api/v1/query \
--data-urlencode 'query=sum by (status) (rate(http_requests_total{namespace="team-blue",job="podinfo"}[1m]))' \
| jq -r '.data.result[] | "\(.metric.status) \(.value[1])"'Expected (numbers vary):
pod/last created
200 4.333333333333332
500 4.106728888888889
Save your progress? Sign up for free
Drill 4: Recording rule and alerting rule
# on cp1
cat > regeln.yaml <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: podinfo
namespace: team-blue
spec:
groups:
- name: podinfo
rules:
- record: namespace_job:http_fehlerquote:rate1m # new time series: share of 5xx
expr: |
sum by (namespace, job) (rate(http_requests_total{job="podinfo", status=~"5.."}[1m]))
/
sum by (namespace, job) (rate(http_requests_total{job="podinfo"}[1m]))
- alert: PodinfoFehlerquoteHoch
expr: namespace_job:http_fehlerquote:rate1m > 0.05 # more than 5 % errors ...
for: 1m # ... for one minute
labels:
severity: warning
team: blue # for routing in Alertmanager
annotations:
summary: "Fehlerquote von {{ $labels.job }} bei {{ $value | humanizePercentage }}"
EOF
k apply -f regeln.yaml
sleep 100
curl -s http://172.16.0.126:30090/api/v1/query --data-urlencode 'query=namespace_job:http_fehlerquote:rate1m' \
| jq -r '.data.result[] | "\(.metric.namespace) \(.metric.job) \(.value[1])"'
curl -s http://172.16.0.126:30090/api/v1/alerts \
| jq -r '.data.alerts[] | select(.labels.alertname=="PodinfoFehlerquoteHoch") | "\(.state) \(.annotations.summary)"'Expected:
prometheusrule.monitoring.coreos.com/podinfo created
team-blue podinfo 0.47959276225357134
firing Fehlerquote von podinfo bei 47.96%
Save your progress? Sign up for free
Drill 5: Alerts to the team
A team gets its alerts at its own receiver – in the lab, a small service that logs every request. The AlertmanagerConfig lives in the team’s namespace; the operator automatically adds a filter on that namespace.
# on cp1
cat > alarm-empfang.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: alarm-empfaenger
namespace: team-blue
spec:
selector:
matchLabels: {app: alarm-empfaenger}
template:
metadata:
labels: {app: alarm-empfaenger}
spec:
containers:
- name: echo
image: mendhak/http-https-echo:43 # logs every request including its body
env: [{name: HTTP_PORT, value: "8080"}]
ports: [{containerPort: 8080}]
---
apiVersion: v1
kind: Service
metadata:
name: alarm-empfaenger
namespace: team-blue
spec:
selector: {app: alarm-empfaenger}
ports: [{port: 8080}]
---
apiVersion: monitoring.coreos.com/v1alpha1
kind: AlertmanagerConfig
metadata:
name: team-blue
namespace: team-blue
spec:
route:
receiver: team-blue-webhook
groupBy: [alertname]
groupWait: 10s # first notification after 10 s
repeatInterval: 1h # repeat while the alert persists
matchers:
- name: team
value: blue
receivers:
- name: team-blue-webhook
webhookConfigs:
- url: http://alarm-empfaenger.team-blue.svc:8080/alarm
EOF
k apply -f alarm-empfang.yaml
k -n team-blue rollout status deploy/alarm-empfaenger --timeout=120s
# Alertmanager lives in monitoring – allow port 8080 too
k -n team-blue patch netpol allow-monitoring --type=json \
-p '[{"op":"add","path":"/spec/ingress/0/ports/-","value":{"port":8080,"protocol":"TCP"}}]'
sleep 90
# received alerts in the receiver's log
k -n team-blue logs deploy/alarm-empfaenger --tail=400 | grep -o -E 'alertname.{0,30}' | head -2
# Alertmanager: which receiver does the alert go to?
curl -s http://172.16.0.126:30093/api/v2/alerts \
| jq -r '.[] | select(.labels.alertname=="PodinfoFehlerquoteHoch") | "\(.status.state) receivers=\(.receivers|map(.name))"'Expected:
alertname\":\"PodinfoFehlerquoteHoch\",\"job\":\"
alertname\":\"PodinfoFehlerquoteHoch\"},\"commonL
active receivers=["team-blue/team-blue/team-blue-webhook"]
The receiver’s name shows its origin:
namespace/AlertmanagerConfig/receiver. What the operator
made of it is in the generated configuration:
# on cp1
k -n monitoring get secret alertmanager-monitoring-kube-prometheus-alertmanager-generated \
-o jsonpath='{.data.alertmanager\.yaml\.gz}' | base64 -d | gunzip | grep -A7 'receiver: team-blue'Expected:
- receiver: team-blue/team-blue/team-blue-webhook
group_by:
- alertname
matchers:
- team="blue"
- namespace="team-blue"
continue: true
group_wait: 10s
The operator added namespace="team-blue": Team Blue
cannot redirect other teams’ alerts.
Save your progress? Sign up for free
Drill 6: A dashboard as code
The Grafana sidecar loads every ConfigMap with the label
grafana_dashboard: "1" as a dashboard.
# on cp1
cat > dashboard.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
name: dashboard-team-blue
namespace: monitoring
labels:
grafana_dashboard: "1"
data:
team-blue.json: |
{
"title": "Team Blue – podinfo",
"uid": "team-blue-podinfo",
"schemaVersion": 39,
"panels": [
{
"type": "timeseries",
"title": "Anfragen pro Sekunde nach Status",
"gridPos": {"x": 0, "y": 0, "w": 12, "h": 8},
"targets": [{"expr": "sum by (status) (rate(http_requests_total{namespace=\"team-blue\",job=\"podinfo\"}[1m]))", "legendFormat": "{{status}}"}]
},
{
"type": "stat",
"title": "Fehlerquote",
"gridPos": {"x": 12, "y": 0, "w": 6, "h": 8},
"fieldConfig": {"defaults": {"unit": "percentunit"}},
"targets": [{"expr": "namespace_job:http_fehlerquote:rate1m{namespace=\"team-blue\"}"}]
}
]
}
EOF
k apply -f dashboard.yaml
sleep 20
# Grafana API: dashboard found?
curl -s -u admin:grafana-lab-123 'http://172.16.0.126:30030/api/search?query=Team%20Blue' | jq -r '.[] | "\(.title) \(.uid)"'Expected:
configmap/dashboard-team-blue created
Team Blue – podinfo team-blue-podinfo
Open http://172.16.0.126:30030/d/team-blue-podinfo –
roughly half of the requests are errors.
Save your progress? Sign up for free
Drill 7: Argo Rollouts asks Prometheus
On Day 5, a Job measured the error rate. With Prometheus, the analysis becomes a query. To try it out without a rollout, you create an AnalysisRun directly – exactly what a rollout does in its analysis step:
# on cp1
cat > analyse-prometheus.yaml <<'EOF'
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: fehlerquote-prometheus
namespace: team-blue
spec:
args:
- name: job
metrics:
- name: fehlerquote
interval: 20s
count: 3
failureLimit: 1
successCondition: result[0] < 0.05 # the query result is a list
provider:
prometheus:
address: http://monitoring-kube-prometheus-prometheus.monitoring.svc:9090
query: namespace_job:http_fehlerquote:rate1m{namespace="team-blue", job="{{args.job}}"}
---
apiVersion: argoproj.io/v1alpha1
kind: AnalysisRun
metadata:
name: test-podinfo
namespace: team-blue
spec:
args:
- name: job
value: podinfo
metrics: # an AnalysisRun carries the metrics itself
- name: fehlerquote
interval: 20s
count: 3
failureLimit: 1
successCondition: result[0] < 0.05
provider:
prometheus:
address: http://monitoring-kube-prometheus-prometheus.monitoring.svc:9090
query: namespace_job:http_fehlerquote:rate1m{namespace="team-blue", job="podinfo"}
EOF
k apply -f analyse-prometheus.yaml
sleep 50
k -n team-blue get analysisrun test-podinfo -o jsonpath='{.status.phase}: {.status.message}{"\n"}'
k -n team-blue get analysisrun test-podinfo \
-o jsonpath='{range .status.metricResults[0].measurements[*]}{.phase} {.value}{"\n"}{end}'Expected:
analysistemplate.argoproj.io/fehlerquote-prometheus created
analysisrun.argoproj.io/test-podinfo created
Failed: Metric "fehlerquote" assessed Failed due to failed (2) > failureLimit (1)
Failed [0.4961230695734457]
Failed [0.48974358974358967]
In the rollout kasse from Day 5, you replace
templateName: fehlerquote with
templateName: fehlerquote-prometheus – provided the
application exposes metrics. The query runs from the controller in
argo-rollouts to Prometheus in monitoring;
team policies are not in the way.
Save your progress? Sign up for free
Exercise: Five queries against the clock
Time limit: 8 minutes. Answer with PromQL in the Prometheus UI:
- How many pods are running per namespace?
- Which node has the least free memory (in GiB)?
- Which containers were restarted in the last hour?
- How many alerts are firing right now?
- What is the CPU usage of
podinforelative to its request?
Solution
1 count by (namespace) (kube_pod_status_phase{phase="Running"} == 1)
2 bottomk(1, node_memory_MemAvailable_bytes / 1024^3)
3 increase(kube_pod_container_status_restarts_total[1h]) > 0
4 count(ALERTS{alertstate="firing"})
5 sum(rate(container_cpu_usage_seconds_total{namespace="team-blue",pod=~"podinfo-.*",container="podinfo"}[5m]))
/ sum(kube_pod_container_resource_requests{namespace="team-blue",pod=~"podinfo-.*",resource="cpu"})
For the exam: rate only on counters
(_total), increase for “how many in time span
X”, by (…) keeps labels, everything else is dropped by
sum.
Save your progress? Sign up for free
Challenge
Time limit: 10 minutes. Stop the load
(k -n team-blue delete pod last) and wait two minutes.
Nobody calls podinfo any more – yet Prometheus keeps
showing requests with status 200, and the error rate is 0 instead of
empty. Where do the requests come from, and what does that mean for
alerts on “too little traffic”?
Solution
# on cp1
k -n team-blue delete pod last
sleep 120
curl -s http://172.16.0.126:30090/api/v1/query \
--data-urlencode 'query=sum by (status) (rate(http_requests_total{namespace="team-blue",job="podinfo"}[1m]))' \
| jq -c '[.data.result[] | [.metric.status, .value[1]]]'
curl -s http://172.16.0.126:30090/api/v1/alerts \
| jq -c '[.data.alerts[] | select(.labels.alertname=="PodinfoFehlerquoteHoch") | .state]'Expected:
[["200","0.1333333333333333"],["500","0"]]
[]
0.133 requests per second = 2 pods × 1 scrape every 15 seconds: that
is Prometheus itself fetching /metrics –
podinfo counts these requests too. The alert disappeared after the load
ended because the error rate is 0. For a “no more traffic” alert,
http_requests_total is unsuitable as it stands: exclude
requests to /metrics (for applications that expose the path
as a label) or use a business metric (orders, logins) – otherwise
monitoring keeps the application artificially “alive”.
Save your progress? Sign up for free
Checkpoint
# on cp1
# no scrape targets down (0)
curl -s 'http://172.16.0.126:30090/api/v1/targets?state=active' | jq '[.data.activeTargets[] | select(.health!="up")] | length'
# rule loaded
curl -s http://172.16.0.126:30090/api/v1/rules | jq -r '.data.groups[] | select(.name=="podinfo") | .rules[].name'
# dashboard present
curl -s -u admin:grafana-lab-123 http://172.16.0.126:30030/api/dashboards/uid/team-blue-podinfo | jq -r .dashboard.titleExpected:
0
namespace_job:http_fehlerquote:rate1m
PodinfoFehlerquoteHoch
Team Blue – podinfo
Interview Note
- Why does a fresh kubeadm cluster show the scheduler and etcd as “down”? They only listen on localhost. Change the bind addresses or deliberately disable the targets.
- ServiceMonitor or scrape configuration in Prometheus? The ServiceMonitor belongs to the team and lives next to the application; Prometheus is not reconfigured for every team.
- What are recording rules for? Compute expensive queries once; dashboards and alerts become faster and consistent; one name instead of a long formula.
Enterprise Note
- Long-term storage and multiple clusters with Thanos or Mimir; Prometheus itself stays short-lived.
- Alert on symptoms (error rate, latency, SLOs with burn rate) instead of causes (high CPU).
- Keep dashboards in Git and roll them out via GitOps; Grafana folders and permissions per team.
- Make control plane metrics reachable only from the management network (firewall on ports 2381, 10257, 10259, 10249); etcd metrics have no authentication.