01 — Observability: metrics¶
The two metrics planes — metrics-server (the resource-metrics API behind
kubectl top/HPA) vs Prometheus (the monitoring TSDB) — Prometheus architecture (pull/scrape, service discovery, TSDB, PromQL, Alertmanager), kube-state-metrics vs node-exporter vs app metrics, the Prometheus Operator + ServiceMonitor/PrometheusRule, the exposition format and RED/USE/four-golden-signals — applied by scraping the Bookstore's existing/metricsand alerting on catalog's error rate.
Estimated time: ~30 min read · ~60 min hands-on
Prerequisites: Part 04 ch.01 — workloads are scheduled and running · Part 05 ch.02 — hardened and running, but is it healthy? · Part 01 ch.02 — probes vs metrics: liveness ≠ p95 latency
You'll know after this: • distinguish metrics-server (resource metrics for HPA) from Prometheus (monitoring TSDB) · • read PromQL for RED, USE and the four golden signals · • deploy the Prometheus Operator and write ServiceMonitor + PrometheusRule resources · • interpret kube-state-metrics, node-exporter and application /metrics together · • alert on the Bookstore catalog's error rate via Alertmanager • lock /metrics to Prometheus and say what the endpoint reveals
Why this exists¶
The Bookstore now runs, is scheduled deliberately (Part 04)
and is hardened (Part 05). The next
question every operator asks is the one Kubernetes itself cannot answer:
is it actually healthy, and how do I know before a user tells me?
kubectl get pods shows Running; it does not show that catalog's p95
latency tripled, that the 5xx rate is climbing, or that a node is saturated.
A Running Pod serving 100% errors is still Running.
Kubernetes ships no built-in monitoring database. It exposes raw signals
(the kubelet's /metrics/resource, the API server's own /metrics, container
cgroup stats) but it does not store history, has no query language, and raises
no alerts. Observability is something you add. This chapter is the metrics
pillar of it (logs are ch.02, traces ch.03);
together they are how you operate the system instead of guessing. This is the
Observability concern from Production Kubernetes.
Mental model¶
There are two distinct metrics planes, and conflating them is the most common beginner mistake:
- The resource-metrics plane —
metrics-server. A single lightweight add-on that scrapes the kubelet Summary API on every node and serves only current CPU/memory per Pod/node through the aggregatedmetrics.k8s.ioAPI. No history (the last data point only), no disk, no query language. It exists for exactly two consumers:kubectl topand the HorizontalPodAutoscaler (ch.04). It is not a monitoring system. - The monitoring plane — Prometheus. A time-series database that
pulls (
scrapes) HTTP/metricsendpoints on an interval, stores the samples with their labels in a local TSDB, and lets you ask questions of the history with PromQL. It evaluates alerting rules and hands firing alerts to Alertmanager for routing. This is the system you graph, alert, and debug with.
You need both: metrics-server because the HPA's Resource metric is fed by
metrics.k8s.io, and Prometheus because that is where SLOs, dashboards and
alerts live. They scrape different things for different consumers and do not
replace each other.
Prometheus's data model: every sample is a metric_name{label=value,...} →
float64 at a timestamp. The Bookstore's Go services already speak it — they
expose http_requests_total{handler,code} (a counter) and
http_request_duration_seconds (a histogram) on /metrics
(app/catalog/main.go). You instrument once in the app; Prometheus does the
rest by scraping.
Three metric sources you will always run, answering different questions:
| Source | What it knows | Example |
|---|---|---|
| Application metrics | what the app is doing | http_requests_total, orders_placed_total |
| kube-state-metrics | the desired/observed state of K8s objects | kube_deployment_status_replicas_available |
| node-exporter | the machine underneath | node_cpu_seconds_total, node_filesystem_avail_bytes |
Threats and controls¶
| Threat | Control in this chapter | Deeper |
|---|---|---|
| Anyone who can reach the metrics port reads route names, traffic and the Go version | A NetworkPolicy admits only the Prometheus pods to :8080 (section 4) |
02.06 |
A public route forwards /metrics to the app |
No Ingress or Gateway rule may deliver it to catalog (section 4 checks the Bookstore's rules and the paths they produce) | 02.04, 02.05 |
| node-exporter needs host networking and host paths, which the baseline forbids | node-exporter gets a namespace of its own, node-exporter, labelled privileged and registered as an exception, with host PID off. monitoring stays restricted (section 2) |
05.02 |
| A Grafana admin password written into a values file or manifest | grafana.admin.existingSecret: the password lives in a Secret you create |
03.02 |
| Personal data or secrets reaching the TSDB through labels | Labels stay bounded (handler, code); log redaction is in 06.02 |
06.02 |
| metrics-server trusting a kubelet it cannot verify | Verification stays on; the insecure flag is never taught | metrics-server FAQ |
Diagrams¶
Prometheus architecture: scrape → store → query → alert (Mermaid)¶
flowchart LR
subgraph cluster["Kubernetes cluster"]
cat["catalog Pods
/metrics :8080"]
ord["orders Pods
/metrics :8080"]
ksm["kube-state-metrics
(object state)"]
subgraph nexns["node-exporter namespace (privileged)"]
nex["node-exporter
DaemonSet (machines)"]
end
subgraph mon["monitoring namespace (restricted)"]
op["Prometheus Operator
(watches CRDs)"]
sm["ServiceMonitor /
PrometheusRule (CRDs)"]
prom["Prometheus
scrape + TSDB + rules"]
am["Alertmanager
(dedupe, route)"]
graf["Grafana
(dashboards)"]
end
end
pager["Pager / Slack / email"]
op -->|"watches CRDs ->
generates scrape + rule config"| sm
op -->|reload| prom
prom -->|pull /metrics| cat
prom -->|pull /metrics| ord
prom -->|pull| ksm
prom -->|pull| nex
prom -->|fires alerts| am
am --> pager
graf -->|PromQL queries| prom
metrics-server vs Prometheus, and RED/USE (ASCII)¶
TWO METRICS PLANES ─────────────────────────────────────────────────────────
metrics-server : kubelet summary -> metrics.k8s.io : NOW only, no history
consumers: `kubectl top`, HPA Resource metric
Prometheus : scrape /metrics -> TSDB (history) -> PromQL/alerts
consumers: Grafana, Alertmanager, you (debugging)
(they do NOT overlap; you run both)
RED — for every REQUEST-serving service (catalog, orders, storefront)
Rate requests/sec sum(rate(http_requests_total[5m]))
Errors failed/sec or ratio rate(...{code=~"5.."}) / rate(...)
Duration latency distribution histogram_quantile(0.95, ...bucket)
USE — for every RESOURCE (node CPU, memory, disk, a queue)
Utilization % time busy / used node_cpu busy ratio
Saturation queued / waiting work runqueue, RabbitMQ queue depth
Errors error events disk errors, OOM kills
The four golden signals (SRE book) = Latency + Traffic + Errors + Saturation
≈ RED (latency/traffic/errors) + the S of USE (saturation).
Hands-on with the Bookstore¶
Assumed working directory: the guide repo root (full-guide/).
We will: (1) install metrics-server and see what its refusal looks like on
kind; (2) install kube-prometheus-stack (Prometheus Operator + Prometheus +
Alertmanager + Grafana + node-exporter + kube-state-metrics) into its own
monitoring namespace, with node-exporter alone in a namespace of its own,
node-exporter; (3) point a ServiceMonitor at catalog's existing
/metrics; (4) lock /metrics down to Prometheus; (5) query it with PromQL;
(6) add a PrometheusRule.
0. Prerequisites (self-bootstrapping — re-run after any kind recreate)¶
# A cluster (single-node kind is fine for this chapter).
kind create cluster --name bookstore
# or: k3d cluster create bookstore --image rancher/k3s:v1.37.1-k3s1
# Build + load the Bookstore images (full instructions in
# examples/bookstore/app/README.md):
cd examples/bookstore/app
docker build -t bookstore/catalog:dev ./catalog
docker build -t bookstore/orders:dev ./orders
docker build -t bookstore/payments-worker:dev ./payments-worker
docker build -t bookstore/storefront:dev ./storefront
cd ../../.. # back to the guide repo root
for i in catalog orders payments-worker storefront; do
kind load docker-image bookstore/$i:dev --name bookstore
done
# The cumulative Bookstore chain, in dependency order (PSA-restricted ns first,
# then SAs, config/secret, cluster-scoped, then workloads + Services):
kubectl apply -f examples/bookstore/raw-manifests/00-namespace.yaml
kubectl apply -f examples/bookstore/raw-manifests/05-serviceaccounts-rbac.yaml
kubectl apply -f examples/bookstore/raw-manifests/15-catalog-config.yaml
kubectl apply -f examples/bookstore/raw-manifests/16-db-credentials.yaml
kubectl apply -f examples/bookstore/raw-manifests/35-priorityclasses.yaml
kubectl apply -f examples/bookstore/raw-manifests/12-redis.yaml
kubectl apply -f examples/bookstore/raw-manifests/13-rabbitmq.yaml
kubectl apply -f examples/bookstore/raw-manifests/20-postgres-statefulset.yaml
kubectl rollout status statefulset/postgres -n bookstore
kubectl apply -f examples/bookstore/raw-manifests/10-catalog-deploy.yaml
kubectl apply -f examples/bookstore/raw-manifests/11-storefront-deploy.yaml
kubectl apply -f examples/bookstore/raw-manifests/14-orders-deploy.yaml
kubectl apply -f examples/bookstore/raw-manifests/40-services.yaml
kubectl apply -f examples/bookstore/raw-manifests/21-db-migrate-job.yaml # schema
# catalog/orders carry DB_DSN; their /readyz pings Postgres connectivity (not
# table existence), so gate on the schema Job BEFORE asserting readiness —
# else they CrashLoop/500 on /books and the rollout wait times out.
kubectl wait --for=condition=complete job/db-migrate -n bookstore --timeout=120s
kubectl rollout status deployment/catalog -n bookstore
1. metrics-server (the resource-metrics plane)¶
Install it with Helm into a namespace of its own, labelled restricted. The
chart's securityContext values already set what restricted asks for
(non-root, a read-only root filesystem, every capability dropped, the
RuntimeDefault seccomp profile), and the install keeps them. The workload does
not go into kube-system, which this chapter does not relabel. The chart still
writes one RoleBinding there, metrics-server-auth-reader, which binds the
extension-apiserver-authentication-reader Role to metrics-server's
ServiceAccount so that it can read the API server's authentication ConfigMap:
kubectl create namespace metrics-server
kubectl label namespace metrics-server \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/warn=restricted
helm repo add metrics-server https://kubernetes-sigs.github.io/metrics-server/
helm repo update
helm install metrics-server metrics-server/metrics-server \
--version 3.14.0 \
--namespace metrics-server
kubectl -n metrics-server get pods
kubectl top nodes
NAME READY STATUS RESTARTS AGE
metrics-server-c4994bc54-b2jpz 0/1 Running 0 53s
error: Metrics API not available
The output in this section came from a lab cluster whose node has a different name from yours. The pod runs, but it does not become ready on this cluster. Read its log to see why:
kubectl -n metrics-server logs deploy/metrics-server --tail=3
E1031 01:17:58.628753 1 scraper.go:149] "Failed to scrape node" err="Get \"https://172.18.0.2:10250/metrics/resource\": tls: failed to verify certificate: x509: cannot validate certificate for 172.18.0.2 because it doesn't contain any IP SANs" node="sf-pilot-control-plane"
The log line is the control working. The kubelet's serving certificate on a
kind node does not list the node's IP address, so metrics-server's
verification refuses it. The tempting fix is --kubelet-insecure-tls, which
turns verification off for every kubelet in the cluster, so this chapter does
not teach it. The metrics-server
FAQ
names the secure setup: validate the kubelet certificate with
--kubelet-certificate-authority, and keep the insecure flags off. Serving
certificates that the cluster CA signs come from the CSR flow. The kubelet
config file turns that flow on with serverTLSBootstrap: true. The
--rotate-server-certificates flag that older guides use is marked deprecated
in favour of that setting (kubelet
reference).
Each serving certificate request then waits for approval, with
kubectl certificate approve, before the kubelet serves its certificate.
A kind configuration would have to set that up, and this lab cluster does not
have one. A second pass meant to build such a cluster and did not start,
because the lab host's container engine did not answer an image listing within
three minutes. So the route is cited here and was not run, and on kind this
chapter stops at the refusal. Chapter 04 step 0 runs the
route on a three-node kind cluster. Until metrics-server
serves, kubectl get apiservice v1beta1.metrics.k8s.io reports False
(MissingEndpoints), and the HPA in ch.04 has no resource
metrics on this cluster.
kubectl top returns current usage only — there is no --since, no
history. That is the entire point of metrics-server: it is the live feed the
HPA samples (ch.04), not a monitoring store.
2. kube-prometheus-stack (the monitoring plane)¶
Install the chart into two namespaces, and neither is bookstore. A
component that needs privilege gets a namespace of its own
(05.02), so that the privilege does not
reach what runs beside it. One component in this stack needs it. node-exporter
is a host-level DaemonSet, and it needs host networking and hostPath
volumes, which restricted and baseline both forbid. Prometheus,
Alertmanager, Grafana, the operator and kube-state-metrics need neither. The
stack therefore splits in two:
| Namespace | Holds | Pod Security labels |
|---|---|---|
monitoring |
Prometheus, Alertmanager, Grafana, the operator, kube-state-metrics | enforce, audit and warn at restricted |
node-exporter |
the node-exporter DaemonSet | enforce at privileged, audit and warn at restricted |
node-exporter is an exception. It is registered in
security/namespace-exceptions.yaml at the repository root, with its reason
and an expiry date. Its warn and audit labels stay at restricted, so the
install prints a warning that names the DaemonSet, and nothing else in the
chart should warn. The chart makes the split a values setting. node-exporter
is a subchart, it takes a namespaceOverride, and the stack passes the values
under prometheus-node-exporter to it. The release goes into monitoring and
Helm creates no other namespace, so create and label both before the install:
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
kubectl create namespace monitoring
kubectl label namespace monitoring \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/warn=restricted
kubectl create namespace node-exporter
kubectl label namespace node-exporter \
pod-security.kubernetes.io/enforce=privileged \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/warn=restricted
kubectl -n monitoring create secret generic grafana-admin \
--from-literal=admin-user=admin \
--from-literal=admin-password="$(openssl rand -base64 24)"
secret/grafana-admin created
The password is generated and never written to a file. Without an
existingSecret, the chart's Grafana subchart writes a random admin password
into a Secret it chooses. Naming your own Secret keeps the password out of the
values file.
The values file moves node-exporter into its namespace. It keeps
node-exporter's host networking and its read-only root mount, which the
network and filesystem collectors read. It turns off the shared host PID
namespace, because the chart's collectors read host data through the /host
mounts instead. Check after install that node_ series still appear. The file
also sets the seccomp and capability fields that the chart exposes:
cat > monitoring-values.yaml <<'EOF'
grafana:
admin:
existingSecret: grafana-admin
prometheus-node-exporter:
namespaceOverride: node-exporter
hostPID: false
securityContext:
seccompProfile:
type: RuntimeDefault
containerSecurityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
EOF
Before installing, render the chart at the pinned version and look at where
each object lands. The first command counts the objects by namespace. The
second lists the chart templates whose output goes to node-exporter:
helm template kube-prometheus-stack prometheus-community/kube-prometheus-stack \
--version 92.16.1 --namespace monitoring --values monitoring-values.yaml \
--skip-tests > kps.yaml
grep -E '^ namespace: ' kps.yaml | sort | uniq -c
awk '/^# Source:/ {src=$3} /^ namespace: node-exporter$/ {print src}' kps.yaml
5 namespace: kube-system
103 namespace: monitoring
4 namespace: node-exporter
kube-prometheus-stack/charts/prometheus-node-exporter/templates/serviceaccount.yaml
kube-prometheus-stack/charts/prometheus-node-exporter/templates/service.yaml
kube-prometheus-stack/charts/prometheus-node-exporter/templates/daemonset.yaml
kube-prometheus-stack/charts/prometheus-node-exporter/templates/servicemonitor.yaml
Four objects moved: node-exporter's ServiceAccount, Service, DaemonSet and
ServiceMonitor. Prometheus still finds the ServiceMonitor, because the
chart's Prometheus selects ServiceMonitors in every namespace
(serviceMonitorNamespaceSelector: {} in the render) by the label
release: kube-prometheus-stack. The five objects in kube-system are the
Services the chart writes for the cluster's own components.
The same render settles the password. The chart writes an admin-password:
line into a Secret only when it makes the Secret itself. With the values file
it makes none. Without existingSecret, the render holds one:
grep -c '^ admin-password:' kps.yaml
helm template kube-prometheus-stack prometheus-community/kube-prometheus-stack \
--version 92.16.1 --namespace monitoring --skip-tests \
| grep -c '^ admin-password:'
With the values file:
0
Without it:
1
The dry run below needs the chart's CRDs in place, because the Prometheus
and ServiceMonitor kinds are theirs. helm install applies the same CRDs
from the chart's crds/ directory. Apply them first, then dry-run the render
against the server. Nothing is created, and the warning reports what
restricted would refuse:
helm show crds prometheus-community/kube-prometheus-stack --version 92.16.1 \
| kubectl apply --server-side --force-conflicts -f -
helm template kube-prometheus-stack prometheus-community/kube-prometheus-stack \
--version 92.16.1 --namespace monitoring --values monitoring-values.yaml \
--skip-tests | kubectl apply --dry-run=server -f -
# ...
Warning: would violate PodSecurity "restricted:latest": host namespaces (hostNetwork=true), restricted volume types (volumes "proc", "sys", "root" use restricted volume type "hostPath")
daemonset.apps/kube-prometheus-stack-prometheus-node-exporter created (server dry run)
# ...
That one warning is the registered exception: host networking and host paths,
reported for the DaemonSet. Every Deployment and Job in monitoring passed
the restricted check that the namespace's warn label runs, and none warned.
--skip-tests leaves out the chart's test hook, which helm test runs and
helm install does not. The dry run cannot judge the Prometheus and
Alertmanager Pods, which the operator creates from their custom resources
after the install, so the install is what tests those. helm show chart
reports the chart as version 92.16.1, which is the version pinned below.
Install the pinned version:
# The release name must be kube-prometheus-stack: the `release:` label on 80-
# and 81- has to match Prometheus's selector (see below).
helm install kube-prometheus-stack \
prometheus-community/kube-prometheus-stack \
--version 92.16.1 \
--namespace monitoring \
--values monitoring-values.yaml \
--wait --timeout 8m
kubectl get pods -n monitoring
kubectl get pods -n node-exporter
The install finished. It ran on a GitHub Actions runner, a machine with 4 vCPU
and about 16 GiB of memory, and --wait returned in under a minute. An earlier
attempt on a lab host with about 3 GiB of memory to spare did not finish: Helm
gave up on Grafana after eight minutes and the control plane restarted while it
ran. The host was too small. Nothing below depends on that attempt. Helm
printed the one warning the dry run predicted, and nothing else warned:
I1031 17:13:47.863359 14211 warnings.go:107] "Warning: would violate PodSecurity \"restricted:latest\": host namespaces (hostNetwork=true), restricted volume types (volumes \"proc\", \"sys\", \"root\" use restricted volume type \"hostPath\")"
NAME: kube-prometheus-stack
LAST DEPLOYED: Sat Oct 31 17:13:42 2026
NAMESPACE: monitoring
STATUS: deployed
REVISION: 1
The two namespaces hold what the table above says. The five Pods in
monitoring are the operator, Prometheus, Alertmanager, Grafana and
kube-state-metrics. Every one was ready when --wait returned. The three
node-exporter Pods, one per node, are in node-exporter:
NAME READY STATUS RESTARTS AGE
alertmanager-kube-prometheus-stack-alertmanager-0 2/2 Running 0 34s
kube-prometheus-stack-grafana-57d9867647-6r2qr 3/3 Running 0 39s
kube-prometheus-stack-kube-state-metrics-78dc75b868-rp4rd 1/1 Running 0 39s
kube-prometheus-stack-operator-dbf7f9444-jrbnf 1/1 Running 0 39s
prometheus-kube-prometheus-stack-prometheus-0 2/2 Running 0 34s
NAME READY STATUS RESTARTS AGE
kube-prometheus-stack-prometheus-node-exporter-686nj 1/1 Running 0 39s
kube-prometheus-stack-prometheus-node-exporter-98tb4 1/1 Running 0 39s
kube-prometheus-stack-prometheus-node-exporter-wbbgq 1/1 Running 0 39s
Read it for the security claim, not only for the ready count. A Pod that a
namespace refuses shows up as a FailedCreate event on its controller, and the
cluster held none:
kubectl get events -A --field-selector reason=FailedCreate
No resources found
So every Pod the install created, among them Prometheus and Alertmanager,
which the dry run could not judge, was admitted by a namespace that enforces
restricted. The DaemonSet in node-exporter keeps host networking, which
its network collectors need, and with hostPID: false it shares no PID
namespace with the node. The empty hostPID below is the unset field, which
means false:
kubectl -n node-exporter get daemonset \
-o jsonpath='{.items[0].metadata.name} hostNetwork={.items[0].spec.template.spec.hostNetwork} hostPID={.items[0].spec.template.spec.hostPID}{"\n"}'
kube-prometheus-stack-prometheus-node-exporter hostNetwork=true hostPID=
Open both UIs through a port-forward, which stays local, and read what
Prometheus scrapes. Its UI is at http://localhost:9090 (Status, then
Targets), and Grafana's is at http://localhost:3000 (user admin; the
password is in grafana-admin):
kubectl -n monitoring port-forward svc/kube-prometheus-stack-prometheus 9090:9090 &
kubectl -n monitoring port-forward svc/kube-prometheus-stack-grafana 3000:80 &
curl -s 'localhost:9090/api/v1/targets?state=active' \
| jq -r '.data.activeTargets[] | [.labels.job, .labels.namespace, .health] | @tsv' | sort
The runner listed 28 active targets, 22 up and 6 down. The
kubelet rows are each node's three paths (metrics, cAdvisor and probes), and
the node-exporter rows are the three DaemonSet Pods in their own namespace:
apiserver default up
coredns kube-system up
coredns kube-system up
kube-controller-manager kube-system down
kube-etcd kube-system down
kube-prometheus-stack-alertmanager monitoring up
kube-prometheus-stack-alertmanager monitoring up
kube-prometheus-stack-grafana monitoring up
kube-prometheus-stack-operator monitoring up
kube-prometheus-stack-prometheus monitoring up
kube-prometheus-stack-prometheus monitoring up
kube-proxy kube-system down
kube-proxy kube-system down
kube-proxy kube-system down
kube-scheduler kube-system down
kube-state-metrics monitoring up
kubelet kube-system up
kubelet kube-system up
kubelet kube-system up
kubelet kube-system up
kubelet kube-system up
kubelet kube-system up
kubelet kube-system up
kubelet kube-system up
kubelet kube-system up
node-exporter node-exporter up
node-exporter node-exporter up
node-exporter node-exporter up
The 6 that are down are the control-plane components and kube-proxy. Their
scrape error is connection refused on the node's address, which is what a
metrics port bound to the loopback address answers. kubeadm, which kind uses,
binds those ports to the loopback address by default. So these 6 fail to
scrape on kind however the chart is installed, and the rows to trust on kind
are the other 22:
curl -s 'localhost:9090/api/v1/targets?state=active' \
| jq -r '.data.activeTargets[] | select(.health!="up") | [.labels.job, .scrapeUrl, .lastError] | @tsv' | sort
kube-controller-manager https://172.18.0.3:10257/metrics Get "https://172.18.0.3:10257/metrics": dial tcp 172.18.0.3:10257: connect: connection refused
kube-etcd http://172.18.0.3:2381/metrics Get "http://172.18.0.3:2381/metrics": dial tcp 172.18.0.3:2381: connect: connection refused
kube-proxy http://172.18.0.2:10249/metrics Get "http://172.18.0.2:10249/metrics": dial tcp 172.18.0.2:10249: connect: connection refused
kube-proxy http://172.18.0.3:10249/metrics Get "http://172.18.0.3:10249/metrics": dial tcp 172.18.0.3:10249: connect: connection refused
kube-proxy http://172.18.0.4:10249/metrics Get "http://172.18.0.4:10249/metrics": dial tcp 172.18.0.4:10249: connect: connection refused
kube-scheduler https://172.18.0.3:10259/metrics Get "https://172.18.0.3:10259/metrics": dial tcp 172.18.0.3:10259: connect: connection refused
Moving node-exporter into its own namespace and turning off the shared PID
namespace must not cost the node metrics. The first query counts the
node_cpu_seconds_total series by the namespace they came from. The second
counts the node-exporter targets that are up:
curl -s 'localhost:9090/api/v1/query' --data-urlencode 'query=count(node_cpu_seconds_total) by (namespace)' \
| jq -r '.data.result[] | [.metric.namespace, .value[1]] | @tsv'
curl -s 'localhost:9090/api/v1/query' --data-urlencode 'query=count(up{job="node-exporter"} == 1)' \
| jq -r '.data.result[0].value[1]'
node-exporter 96
3
Grafana's login is the second claim. The first request below carries no
credentials, and a 401 means the login is enforced. A refusal proves
something only if a request with the right credentials is accepted, so the
second request reads the generated password from the Secret into a shell
variable and sends it. The status line is all that prints, and the password is
never shown:
curl -s -o /dev/null -w '%{http_code}\n' localhost:3000/api/org
GPW=$(kubectl -n monitoring get secret grafana-admin -o jsonpath='{.data.admin-password}' | base64 -d)
curl -s -o /dev/null -w '%{http_code}\n' -u "admin:$GPW" localhost:3000/api/org
unset GPW
401
200
3. Scrape the Bookstore: a ServiceMonitor¶
Prometheus does not scrape catalog at this point in the chapter. We do not edit
prometheus.yml — the Operator turns a ServiceMonitor custom resource into
scrape config. New file
examples/bookstore/raw-manifests/80-servicemonitor.yaml
(catalog shown; the file also includes payments-worker):
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: catalog
namespace: bookstore
labels:
app: catalog
release: kube-prometheus-stack # MUST match Prometheus's serviceMonitorSelector
spec:
selector:
matchLabels: { app: catalog } # selects the `catalog` Service (40-)
namespaceSelector:
matchNames: ["bookstore"]
endpoints:
- port: http # the catalog Service's named port (-> 8080)
path: /metrics # promhttp.Handler() (app/catalog/main.go)
interval: 15s
The
release:label is load-bearing. kube-prometheus-stack's Prometheus defaults toserviceMonitorSelector: matchLabels: {release: kube-prometheus-stack}. A ServiceMonitor without that label is a valid object that is silently never scraped — the single most common "my ServiceMonitor does nothing" cause. The file's header documents this.CRD-backed object — expected dry-run note.
ServiceMonitoris a Prometheus Operator CRD, not a built-in kind. On a cluster without the Operator,kubectl apply --dry-run=client -f 80-servicemonitor.yamlprintsno matches for kind "ServiceMonitor" in version "monitoring.coreos.com/v1"— expected and not a defect, exactly like the Gateway API (Part 02 ch.05), VolumeSnapshot (Part 03 ch.05) and Kyverno (Part 05 ch.07) objects. After installing the stack the schema is valid and it applies. The same applies to81-prometheusrule.yaml.
kubectl apply -f examples/bookstore/raw-manifests/80-servicemonitor.yaml
# Prometheus UI -> Status -> Targets: bookstore/catalog should be UP within ~30s.
On the runner the stack was running, and 60-networkpolicy.yaml from section 4
was already applied. The apply created both objects:
servicemonitor.monitoring.coreos.com/catalog created
servicemonitor.monitoring.coreos.com/payments-worker created
Within a minute Prometheus listed catalog's Pods as targets, and every one was
up. They are up behind the default-deny policy because rule 10 admits the real
Prometheus Pod, the one the label app.kubernetes.io/name=prometheus selects:
kubectl -n monitoring get pods -l app.kubernetes.io/name=prometheus
curl -s 'localhost:9090/api/v1/targets?state=active' \
| jq -r '.data.activeTargets[] | select(.labels.namespace=="bookstore") | [.labels.job, .labels.namespace, .health] | @tsv' | sort
NAME READY STATUS RESTARTS AGE
prometheus-kube-prometheus-stack-prometheus-0 2/2 Running 0 3m11s
catalog bookstore up
catalog bookstore up
catalog bookstore up
NetworkPolicy interaction. Once a policy-enforcing CNI is in play (Part 02 ch.06), default-deny ingress in
bookstoreblocks Prometheus's scrape and every target shows "context deadline exceeded". Rule 10 of60-networkpolicy.yaml(allow-monitoring-scrape) admits only the Prometheus pods inmonitoringto catalog, orders and payments-worker on:8080. Section 4 applies it. Note this rule is deliberately one-sided — unlike the intra-bookstorebackend edges (Part 02 ch.06), which need both a destination Ingress and a source Egress rule because both endpoints sit in the default-denybookstorenamespace. This scrape edge is cross-namespace: the source (Prometheus) lives inmonitoring, which kube-prometheus-stack does not put under a default-deny policy, so Prometheus already has unrestricted egress and needs no egress rule. NetworkPolicy is per-namespace; only the locked-down side (bookstore) has a half to add, so the missing "other half" is correct by design, not an omission.
4. Lock /metrics to Prometheus¶
catalog serves /metrics on the port its API uses, :8080, and nothing
authenticates the request. Before a NetworkPolicy exists, a pod in any namespace
can read it. The probe below stands in for such a pod. It runs as UID 100 and
GID 101, which the curl image declares, with the restricted settings from the
baseline:
kubectl create namespace probe
kubectl label namespace probe \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/warn=restricted
kubectl -n probe create serviceaccount probe
# curlimages/curl:8.10.1, pinned by digest
kubectl run probe -n probe --rm -i --restart=Never \
--image=curlimages/curl@sha256:d9b4541e214bcd85196d6e92e2753ac6d0ea699f0af5741f8c6cccbfcf00ef4b \
--overrides='{"spec":{"serviceAccountName":"probe","automountServiceAccountToken":false,"securityContext":{"runAsNonRoot":true,"runAsUser":100,"runAsGroup":101,"seccompProfile":{"type":"RuntimeDefault"}},"containers":[{"name":"probe","image":"curlimages/curl@sha256:d9b4541e214bcd85196d6e92e2753ac6d0ea699f0af5741f8c6cccbfcf00ef4b","command":["curl","-sS","-m","5","http://catalog.bookstore.svc.cluster.local/metrics"],"resources":{"requests":{"cpu":"10m","memory":"16Mi"},"limits":{"memory":"32Mi"}},"securityContext":{"allowPrivilegeEscalation":false,"readOnlyRootFilesystem":true,"capabilities":{"drop":["ALL"]}}}]}}'
# HELP go_info Information about the Go environment.
# TYPE go_info gauge
go_info{version="go1.26.10"} 1
Most of the body is runtime detail. go_info gives the Go version, which is
enough to match a runtime advisory. The handler and code labels name each
route and status the app serves, and the counters show the traffic per route.
The health endpoints already show traffic before any load, because the
kubelet's probes call healthz and readyz:
http_requests_total{code="200",handler="healthz"} 4
http_requests_total{code="200",handler="readyz"} 8
The labels hold no customer data, but the counters still show how busy the
service is. The other services add business volume to the same kind of
endpoint, as orders_placed_total and payments_processed_total. Any pod that
reaches the port reads all of it.
Apply the lock. Rule 10 admits the Prometheus pods and nothing else in
monitoring:
kubectl apply -f examples/bookstore/raw-manifests/60-networkpolicy.yaml
networkpolicy.networking.k8s.io/default-deny-all created
# ...
networkpolicy.networking.k8s.io/allow-monitoring-scrape created
Rule 10 is the only edge into monitoring, and its from entry needs both
selectors. Two stand-in pods in that namespace show it. The first carries
app.kubernetes.io/name: prometheus, the label to check on the chart's real
Prometheus pods with kubectl -n monitoring get pods --show-labels once the
stack runs. The second carries a Grafana label. The stand-ins need no stack,
so they test the rule's selectors on their own, and section 3 showed the same
rule admitting the real Prometheus Pod. node-exporter is not part of it: the
DaemonSet lives in its own namespace and is not a source this rule admits.
kubectl -n monitoring create serviceaccount standin
kubectl run prometheus-standin -n monitoring --labels=app.kubernetes.io/name=prometheus \
--rm -i --restart=Never --image=curlimages/curl@sha256:d9b4541e214bcd85196d6e92e2753ac6d0ea699f0af5741f8c6cccbfcf00ef4b \
--overrides='{"spec":{"serviceAccountName":"standin","automountServiceAccountToken":false,"securityContext":{"runAsNonRoot":true,"runAsUser":100,"runAsGroup":101,"seccompProfile":{"type":"RuntimeDefault"}},"containers":[{"name":"prometheus-standin","image":"curlimages/curl@sha256:d9b4541e214bcd85196d6e92e2753ac6d0ea699f0af5741f8c6cccbfcf00ef4b","command":["curl","-sS","-m","5","-o","/dev/null","-w","%{http_code}\n","http://catalog.bookstore.svc.cluster.local/metrics"],"resources":{"requests":{"cpu":"10m","memory":"16Mi"},"limits":{"memory":"32Mi"}},"securityContext":{"allowPrivilegeEscalation":false,"readOnlyRootFilesystem":true,"capabilities":{"drop":["ALL"]}}}]}}'
kubectl run grafana-standin -n monitoring --labels=app.kubernetes.io/name=grafana \
--rm -i --restart=Never --image=curlimages/curl@sha256:d9b4541e214bcd85196d6e92e2753ac6d0ea699f0af5741f8c6cccbfcf00ef4b \
--overrides='{"spec":{"serviceAccountName":"standin","automountServiceAccountToken":false,"securityContext":{"runAsNonRoot":true,"runAsUser":100,"runAsGroup":101,"seccompProfile":{"type":"RuntimeDefault"}},"containers":[{"name":"grafana-standin","image":"curlimages/curl@sha256:d9b4541e214bcd85196d6e92e2753ac6d0ea699f0af5741f8c6cccbfcf00ef4b","command":["curl","-sS","-m","5","-o","/dev/null","-w","%{http_code}\n","http://catalog.bookstore.svc.cluster.local/metrics"],"resources":{"requests":{"cpu":"10m","memory":"16Mi"},"limits":{"memory":"32Mi"}},"securityContext":{"allowPrivilegeEscalation":false,"readOnlyRootFilesystem":true,"capabilities":{"drop":["ALL"]}}}]}}'
200
The labelled stand-in gets 200. The other is refused although it sits in the
same namespace. That is what the single from entry does. Two list items
would have admitted both pods.
000
curl: (28) Connection timed out after 5002 milliseconds
Run the same probe again:
curl: (28) Connection timed out after 5001 milliseconds
Exit code 28 is curl's timeout, and it is the result the policy should give. The
Bookstore's default-deny ingress has no rule that admits pods in probe, so the
connection is dropped and never answered.
Rule 4 still admits storefront to the same port, for the API. A NetworkPolicy matches pods and ports, never URL paths, so storefront reads the same endpoint:
kubectl -n bookstore exec deploy/storefront -- wget -q -O - http://catalog/metrics
# HELP go_info Information about the Go environment.
# TYPE go_info gauge
go_info{version="go1.26.10"} 1
That is the residual exposure, and the lock does not close it. The fix is a metrics port that only Prometheus can reach, or a layer-7 policy that matches the path. This chapter builds neither: catalog serves its metrics on the same port as its API, so the lock above is the only control on that port.
The public route. No Ingress or Gateway rule may send /metrics to the
app, and the edge the guide builds keeps that rule. Check it against the
manifests, not against memory. The Ingress in
02.04 has three Prefix paths: /api/books
to catalog, /api/orders to orders and / to storefront. Its optional
Traefik Middleware rewrites ^/api/(books|orders)(.*) to /$1$2, so the
output always starts with /books or /orders and no input can produce
/metrics. Without the Middleware the path reaches catalog unchanged, as
/api/books/metrics. The Gateway in 02.05
rewrites the prefix /api/books to /books, which gives the same result. A
request for /metrics on the public host matches only the / path, so it
reaches storefront, which serves its page. Neither rewrite lands on a route
catalog has: it answers GET /metrics at the root and GET /books as an exact
path (Go ServeMux patterns),
so /books/metrics and /api/books/metrics are both not found.
No Traefik ran on the lab cluster for this chapter, so no request went through
the edge. The edge half above is read from the manifests. The catalog half
ran: the lab sent the three paths below to a build of app/catalog on a
workstation, which serves the same routes as the Pod. On your cluster, send
the same paths to the Service through a port-forward:
kubectl -n bookstore port-forward svc/catalog 18080:80 &
for p in /metrics /books/metrics /api/books/metrics; do
curl -s -o /dev/null -w "%{http_code} $p\n" "http://localhost:18080$p"
done
kill %1
200 /metrics
404 /books/metrics
404 /api/books/metrics
Only the first path is the real endpoint, and the edge has no way to produce
it. The change that would break that is a rewrite that drops /books, such as
a stripPrefix of /api/books, which turns /api/books/metrics into
/metrics. Repeat the loop after any change to a route or a Middleware, and
request /metrics through the public host as well, to confirm that the edge
answers with storefront's page and not with the metrics body.
09.01 measured the
edge half. With Traefik and the rewrite running on a runner, /metrics on the
public host returned storefront's page with no go_info line, and
/api/books/metrics and /api/orders/metrics both returned 404.
5. Query the Bookstore with PromQL¶
Generate traffic from storefront, the one caller the policy admits. catalog is
distroless (no shell), so the load cannot run inside it. Storefront's image has
a shell and BusyBox wget:
kubectl -n bookstore exec deploy/storefront -- \
sh -c 'for i in $(seq 1 200); do wget -q -O /dev/null http://catalog/books; done; echo done'
done
-q hides failed requests, so check the counters rather than the loop's count.
Then query (Prometheus UI → Graph, or /api/v1/query). A throwaway pod would be
refused by the same policy, which is the point of the lock.
The RED queries (these work against the metrics catalog already exports):
# Rate — requests/sec to the books handler, per pod, last 5m
sum(rate(http_requests_total{handler="books"}[5m])) by (pod)
# Errors — 5xx ratio across catalog (the SLO-style symptom signal)
sum(rate(http_requests_total{handler!="metrics",code=~"5.."}[5m]))
/ sum(rate(http_requests_total{handler!="metrics"}[5m]))
# Duration — p95 latency from the histogram (the standard quantile pattern)
histogram_quantile(0.95,
sum by (le) (rate(http_request_duration_seconds_bucket{handler="books"}[5m])))
In Grafana, the bundled "Kubernetes / Compute Resources" dashboards already work (kube-state-metrics + node-exporter feed them); build a Bookstore RED dashboard from the three queries above (one panel each).
6. Alert on catalog's error rate: a PrometheusRule¶
New file
examples/bookstore/raw-manifests/81-prometheusrule.yaml
(one rule shown; the file has three — high error rate, high p95, absent):
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: bookstore-catalog-rules
namespace: bookstore
labels:
app: catalog
release: kube-prometheus-stack # MUST match Prometheus's ruleSelector
spec:
groups:
- name: bookstore-catalog.rules
rules:
- alert: CatalogHighErrorRate
expr: |
(sum(rate(http_requests_total{handler!="metrics",code=~"5.."}[5m]))
/ sum(rate(http_requests_total{handler!="metrics"}[5m]))) > 0.05
for: 10m
labels: { severity: warning, service: catalog }
annotations:
summary: "catalog 5xx error ratio above 5%"
kubectl apply -f examples/bookstore/raw-manifests/81-prometheusrule.yaml
# Prometheus UI -> Alerts: the 3 rules appear (Inactive until the expr trips,
# then Pending for `for:` 10m, then Firing -> Alertmanager).
On the runner Prometheus loaded all three rules from the PrometheusRule. The API reports each one healthy and not firing, as it should while catalog serves no errors:
curl -s 'localhost:9090/api/v1/rules' \
| jq -r '.data.groups[] | select(.name=="bookstore-catalog.rules") | .rules[] | [.name, .state, .health] | @tsv'
CatalogHighErrorRate inactive ok
CatalogHighLatencyP95 inactive ok
CatalogAbsent inactive ok
for: 10m means the condition must hold continuously for 10 minutes before
firing — this is what stops a momentary blip from paging anyone. The
thresholds here are illustrative; ch.05
derives them from an actual SLO and error budget.
How it works under the hood¶
- Pull, not push. Prometheus scrapes: it issues an HTTP
GET /metricsto each target everyscrape_intervaland parses the text exposition format (name{labels} value [timestamp],# HELP,# TYPE). Pull means Prometheus controls the load and target discovery, and a target being unreachable is itself a signal (up == 0). The Bookstore'spromhttp.Handler()is the exposition endpoint; the client library tracks counters/histograms in memory and renders them on each scrape. - Service discovery, not a static list. In Kubernetes, Prometheus uses
the
kubernetes_sddiscovery role to enumerate Pods/Services/Endpoints from the API server and relabels them into targets. The Prometheus Operator sits on top: it watchesServiceMonitor/PodMonitor/PrometheusRuleobjects and generates the scrape and rule config, then triggers a Prometheus config reload. You manage Kubernetes objects; the Operator managesprometheus.yml. That is why adding a target iskubectl applyof a ServiceMonitor, never editing a config file. - The TSDB. Samples append to a per-series in-memory head block, flushed to immutable on-disk blocks (default 2h) with a WAL for crash recovery; old blocks are compacted and expire at the retention horizon (default 15d — Prometheus is not long-term storage; that is Thanos/Cortex/Mimir). Each unique label-set is its own series.
- PromQL evaluates over the series.
rate()needs a counter (the client library guarantees monotonicity;ratecorrects for counter resets/restarts). A histogram is exposed as cumulative_bucket{le=...}series plus_sum/_count;histogram_quantile(0.95, sum by (le) (rate( ..._bucket[5m])))interpolates the p95 from the bucket rates. This is why the app exports a histogram, not a single latency gauge — quantiles must be computed from the distribution, and cannot be averaged across pods. - Rules and Alertmanager. Prometheus evaluates each rule group on an
interval. A recording rule precomputes an expensive expression into a new
series; an alerting rule whose
expris non-empty for itsfor:duration becomes a firing alert sent to Alertmanager, which deduplicates, groups, silences, and routes (pager/Slack/email). Alertmanager does the routing; Prometheus only decides what is firing. - Cardinality is the failure mode. Series count = product of every
label's distinct values. A label with unbounded values (user ID, full
URL, request UUID) multiplies series without limit and OOMs Prometheus.
The Bookstore deliberately labels by bounded dimensions (
handler,code) — never the book ID or a raw path. High cardinality is the number one way people take Prometheus down.
Production notes¶
In production: keep the two planes separate and do not skip either.
metrics-server(or a cloud equivalent) is mandatory forkubectl topand any HPA Resource metric (ch.04); Prometheus (or a managed equivalent) is mandatory for SLOs and alerting. Removing metrics-server silently breaks autoscaling; relying on it for monitoring gives you no history at all.In production: instrument with RED for every request service and USE for every resource, and alert on symptoms (error ratio, latency, SLO burn) not causes (CPU high). A CPU alert pages you when nothing is wrong and stays silent when the app is broken but cheap. The Bookstore's
81-prometheusrule.yamlalerts on error ratio and p95 — the things a user feels.In production: managed offerings change the operator/scaler you run, not the model. EKS: Amazon Managed Service for Prometheus + the CloudWatch agent / ADOT collector; GKE: Google Cloud Managed Service for Prometheus (drop-in, keeps PromQL + ServiceMonitor-style config); AKS: Azure Monitor managed Prometheus + Managed Grafana. They all ingest the same exposition format — your app instrumentation and PromQL are portable; only the install and long-term storage differ.
In production: put retention and long-term storage in the design from day one. Local Prometheus retention is days; for months/years and HA, federate to Thanos/Cortex/Mimir (or the managed equivalents). Size Prometheus by active series and watch
prometheus_tsdb_head_series; guard cardinality withmetric_relabel_configsthat drop dangerous labels.In production: scrape kube-state-metrics and node-exporter, not just apps. Most "why did the Pod restart / why was it evicted / is the node saturated" questions are answered by
kube_*andnode_*series, not application metrics — they are the USE half of the picture.
Quick Reference¶
kubectl top nodes ; kubectl top pods -n bookstore # metrics-server plane
kubectl get servicemonitor,prometheusrule -n bookstore # Operator CRDs
kubectl -n monitoring port-forward svc/kube-prometheus-stack-prometheus 9090:9090
kubectl -n monitoring port-forward svc/kube-prometheus-stack-grafana 3000:80
# Prometheus UI: Status->Targets (is catalog UP?), Alerts (rule state)
sum(rate(http_requests_total{handler="books"}[5m])) # Rate
sum(rate(http_requests_total{code=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) # Errors
histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))) # Duration
up{job="catalog"} # is it scraped?
Minimal ServiceMonitor + alerting rule skeleton:
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata: { name: x, namespace: ns, labels: { release: kube-prometheus-stack } }
spec:
selector: { matchLabels: { app: x } }
endpoints: [{ port: http, path: /metrics, interval: 15s }]
---
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata: { name: x, namespace: ns, labels: { release: kube-prometheus-stack } }
spec:
groups:
- name: x.rules
rules:
- alert: XHighErrors
expr: rate(http_requests_total{code=~"5.."}[5m]) > 0
for: 10m
labels: { severity: warning }
Checklist:
- metrics-server installed (
kubectl topworks) — HPA prerequisite - Prometheus stack in its own
monitoringnamespace, labelledrestricted - App exposes
/metrics; labels are bounded (no IDs/paths) - ServiceMonitor carries the
release:label Prometheus selects on - Alerts are symptom-based (errors/latency/SLO), not CPU
- NetworkPolicy admits only the Prometheus pods to app
:8080 - No Ingress or Gateway rule matches
/metrics - node-exporter alone is in the privileged
node-exporternamespace, a registered exception; Grafana's login is a Secret - Retention/long-term storage and cardinality budget decided
Test your understanding¶
Try each before opening the answer drawer. The act of trying is the exercise; the answer is the check.
-
kubectl top podsworks and shows live CPU/memory. Does that mean Prometheus is also installed? Explain in one sentence.
Show answer
No — `kubectl top` is served by **metrics-server** via the `metrics.k8s.io` aggregated API, which is a separate lightweight add-on for *current* CPU/memory only (no history, no alerts, no PromQL). Prometheus is a separate monitoring TSDB; you can have either, both, or — in production — both, because they answer different questions. See the table in §Mental model. -
You write
up{job="catalog"} == 0as an alerting rule and it never fires, even though you cankubectl get podsand see catalog pods crashing. Where would you look first?
Show answer
`up` is the scrape result — if the *ServiceMonitor* doesn't select the pod's Service (label mismatch on `release:` or `app:`), Prometheus never tries to scrape it, so there's no `up{job="catalog"}` series at all (vs being 0). Check Prometheus UI → Status → Targets: if catalog isn't listed, it's a ServiceMonitor selector or `prometheus.spec.serviceMonitorSelector` mismatch. The trap is "no data" looks identical to "everything's healthy" — alert on **absence** with `absent(up{job="catalog"})`, not just `== 0`. -
Your
http_requests_totalseries has labels{handler, code, customer_id}. After a week Prometheus is OOMing and queries are slow. What's the root cause and the fix?
Show answer
`customer_id` is unbounded. Every customer creates a new time series, and Prometheus's memory cost is proportional to *active series count*, not request volume. This is **label cardinality explosion**, the #1 way to break a Prometheus. Fix: drop `customer_id` from the metric (it belongs in *logs* or *traces*, not metrics), keep labels to a small, fixed set of values (`handler`, `code`, `method`). -
Hands-on extension — break a histogram. Define an HPA that uses
http_request_duration_seconds(a histogram) as a custom metric without first exposing_bucket,_sum,_count. Apply it. What doeskubectl describe hpashow?
What you should see
The HPA stays at `Unknown` for the metric value; `kubectl describe hpa` shows `FailedGetExternalMetric` / `unable to fetch metrics`. Histograms are aggregated via `histogram_quantile(0.95, sum by (le) (rate(..._bucket[5m])))` — you cannot point HPA at a raw histogram. Either expose a derived `_p95` gauge via a recording rule, or use the Prometheus Adapter to register the quantile as an external metric. -
Why does the chapter insist that alerts be symptom-based (errors/latency/SLO) rather than CPU-based?
Show answer
High CPU is not a symptom of user pain — a pod can run at 90% CPU and serve perfect p95 latency; a pod at 10% CPU can be erroring every request. CPU alerts produce paging noise (false positives) *and* miss real failures (false negatives). Alert on **what users feel** (error rate, latency, throughput drop) — the four golden signals / RED — and use CPU as a *diagnostic* once you're already paged on a symptom. -
A teammate wants an Ingress rule for
/api/books/metrics, so the dashboard team can read catalog's metrics from outside the cluster. What do you tell them, and what do you check before approving it?
Show answer
Say no. `/metrics` has no authentication, and it reveals the Go version, the route names and the traffic per route. The Bookstore's Ingress already matches `/api/books/metrics`, because `/api/books` is a `Prefix` path, but catalog answers 404 to it, both with the Middleware (`/books/metrics`) and without it (`/api/books/metrics`). The teammate's request is therefore a request to add a rewrite whose output is `/metrics`, and that is the change to refuse. Give the dashboard team Grafana, which has its own login, and keep the scrape inside the cluster. Before approving any route or Middleware, work out what path catalog would receive for `/api/books/metrics`, including `stripPrefix` Middlewares and regex captures such as `(.*)`, and send that request to catalog to see the status. -
node-exporter needs host networking and host paths. A teammate suggests labelling
monitoringasprivilegedso the whole stack installs in one namespace. What is wrong with that, and what does the chart give you instead?
Show answer
Pod Security labels work per namespace, and they select a level with nothing in between ([05.02](../05-security/02-pod-security.md)). A `privileged` `monitoring` would stop checking Prometheus, Alertmanager, Grafana, the operator and kube-state-metrics, and any Pod created there later, to give one DaemonSet what it needs. The chart's `prometheus-node-exporter.namespaceOverride` puts that DaemonSet in a namespace of its own, `node-exporter`. That namespace is labelled `privileged`, registered with a reason and an expiry, and keeps audit and warn at `restricted`, so the DaemonSet's warning stays visible. `monitoring` stays `restricted`.
Further reading¶
- Rosso et al., Production Kubernetes, ch.9 — Observability (metrics pipeline, Prometheus, alerting, the RED/USE framing for a platform).
- Ibryam & Huß, Kubernetes Patterns 2e — Predictable Demands (ch.2) for why measured resource behaviour (not guesses) underpins scaling and capacity (ch.04, ch.06).
- Official: https://kubernetes.io/docs/tasks/debug/debug-cluster/resource-metrics-pipeline/
(metrics-server /
metrics.k8s.io), https://prometheus.io/docs/introduction/overview/ and the Prometheus Operator design: https://prometheus-operator.dev/docs/getting-started/introduction/. - metrics-server's secure setup, https://github.com/kubernetes-sigs/metrics-server/blob/master/FAQ.md, and kubelet serving certificates, https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/.