Our obs layer installs kube-prometheus-stack, which bundles three distinct pieces people often blur together: Prometheus itself, the Prometheus Operator that wires it via CRDs, and a set of exporters and dashboards. On the exam you'll drive everything through those operator CRDs, so that's the layer to get fluent in.
make up obsOrientation
Two core skills drive this whole domain: getting a target scraped cleanly, and writing a PromQL query that answers a real question. Alerting, dashboards, DORA metrics, and incident debugging all sit right on top of those two.
Prometheus scrapes HTTP endpoints on a schedule and writes samples into its local TSDB. Every unique combination of metric name plus label values creates a separate time series, which is why label cardinality is your primary scaling limit. Kubernetes service discovery feeds Prometheus the list of targets, relabeling filters and rewrites them, and each scrape records either success (up = 1) or failure (up = 0). Because nothing is pushed, short-lived batch jobs vanish unseen unless they report through a Pushgateway or emit an event elsewhere.
The operator model
Instead of hand-editing prometheus.yml, you declare what to scrape with CRDs. A ServiceMonitor targets endpoints behind Services matching specific labels (by port name, path, and interval). A PodMonitor scrapes pods directly without needing a Service. A ScrapeConfig reaches targets outside Kubernetes, and a Probe drives blackbox-exporter checks. The operator watches all of them and reloads Prometheus's config automatically.
ServiceMonitor (selector: app=example, port: web, path: /metrics)
│ matched by Prometheus.spec.serviceMonitorSelector ← the filter people forget
▼
Service app=example, ports: [{name: web, port: 8080}]
│ its EndpointSlice supplies the actual pod IPs
▼
pod:8080/metrics ──scraped every 30s──▶ series {job="example", namespace=…, pod=…}
Prometheus only watches ServiceMonitors matching its own serviceMonitorSelector. On a stock kube-prometheus-stack install, that requires the Helm release label (release: prometheus). Miss it, and your perfectly valid monitor gets silently ignored with zero errors and zero targets. Our lab turns that filter off (serviceMonitorSelectorNilUsesHelmValues=false) so {} picks up everything, but don't assume the exam cluster did. Always inspect the Prometheus selector first, then write the monitor.
kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.serviceMonitorSelector}'; echo
kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.serviceMonitorNamespaceSelector}'; echooutputcaptured 2026-08-26
$ kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.serviceMonitorSelector}'; echo
{}
$ kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.serviceMonitorNamespaceSelector}'; echo
{}Here it prints {}; on a default chart install it prints the release-label matcher. Check the namespace selector right beside it too, because a monitor living in a namespace Prometheus doesn't watch is just as invisible.
The other three reasons a target goes missing
- Port name, not number.
endpoints[].portexpects the Service's port name. Leave the Service port unnamed and the monitor silently finds nothing to scrape. - No ready endpoints. The Service selector doesn't match any Ready pods (section 1.1): same empty target list, different root cause.
- RBAC or NetworkPolicy. Prometheus's ServiceAccount needs permission to list endpoints in the target namespace, and default-deny tenant namespaces need an explicit ingress rule allowing traffic from
monitoring.
Keep your debugging order simple: open Status → Targets in the Prometheus UI (it prints the exact failure reason), query up{job="…"}, then walk through those four checks.
Relabeling at exam depth
relabelings transform discovered targets before scraping (drop targets, rewrite job or namespace labels), while metricRelabelings filter samples after scraping. Keep one rescue move in your back pocket: dropping a noisy high-cardinality metric at ingestion using action: drop on a __name__ regex can save a struggling Prometheus instance on the spot.
PromQL: the practical working subset
| Type | Read it with | Example |
|---|---|---|
| Counter (monotonic, resets to 0) | rate() · increase() | rate(http_requests_total[5m]) |
| Gauge (goes up and down) | read directly | kube_pod_status_ready |
| Histogram (cumulative buckets) | histogram_quantile() | histogram_quantile(0.95, sum by (le) (rate(x_bucket[5m]))) |
| Summary (pre-computed quantiles) | filter on quantile | x{quantile="0.99"} |
- Selectors:
up{namespace="argocd"}using=,!=,=~, or!~. Prometheus regexes are automatically anchored end to end. - Ranges: adding
[5m]turns an instant vector into a range vector forrate,increase, and*_over_time. Passing a range vector where an instant vector is expected throws "expected type instant vector." - Aggregation:
sum by (label) (...)keeps only listed labels;sum without (pod) (...)keeps everything else. Never sum before taking a rate: alwaysrate()first, thensum(). - Vector math joins series with identical label sets; mismatched labels produce empty output unless you add
on()/ignoring()andgroup_left(just like the cost gap query in section 1.5). - Handling missing series:
absent(x)returns 1 when x disappears entirely (essential for dead-target alerts), and… or vector(0)turns empty results into a clean zero for stat panels. ratevs.irate:rateaverages across the full window (use for alerts and graphs), whileirateonly looks at the last two samples (great for sharp spikes, terrible for alerts).increaseisrate × window, ideal for totals like "deployments in the last 24h."
See why raw counters mislead and how your lookback window changes the curve:
up metric
Every healthy target emits 1 and every failed scrape emits 0, making count(up == 0) the quickest health check on the cluster. make validate asserts it returns zero (which is why our lab patches kubeadm's localhost-bound control-plane metrics via make fix-cp-metrics). Any "is monitoring healthy?" question starts right here.
Metrics you already get for free
| Source | Gives you | Typical series |
|---|---|---|
| kube-state-metrics | Kubernetes object state from the API server | kube_pod_info, kube_deployment_status_replicas_unavailable, kube_pod_container_status_restarts_total |
| cAdvisor (kubelet) | live container resource consumption | container_cpu_usage_seconds_total, container_memory_working_set_bytes |
| node-exporter | host-level OS and disk metrics | node_load1, node_filesystem_avail_bytes |
| kubelet / apiserver | control-plane health and request latency | apiserver_request_duration_seconds_bucket |
Because these ship out of the box, you almost never need custom app instrumentation to answer cluster-level exam prompts.
The rest of the Prometheus Operator CRDs
Every operator CRD plugs into Prometheus through a matched pair of selectors (label selector + namespace selector), and every single one fails silently the exact same way when either half doesn't match. Keep this lookup table handy:
| Kind | Selected by | Scrapes | Key field to watch |
|---|---|---|---|
| ServiceMonitor | serviceMonitorSelector / serviceMonitorNamespaceSelector | endpoints behind matching Services | endpoints[].port expects a port name (use targetPort for numbers) |
| PodMonitor | podMonitorSelector / podMonitorNamespaceSelector | pods directly, no Service needed | podMetricsEndpoints[].port takes container port name (portNumber for numbers) |
| Probe | probeSelector / probeNamespaceSelector | blackbox-exporter synthetic checks | prober.url (the exporter), targets.staticConfig.static[] or targets.ingress, module |
| ScrapeConfig | scrapeConfigSelector / scrapeConfigNamespaceSelector | anything: staticConfigs, kubernetesSDConfigs, httpSDConfigs, fileSDConfigs, dnsSDConfigs, Consul/cloud SD | raw scrape_config in CRD form, perfect for external VMs, databases, or role: node discovery |
| PrometheusRule | ruleSelector / ruleNamespaceSelector | nothing; evaluated as rules | covered in section 4.2 |
| AlertmanagerConfig | alertmanagerConfigSelector / alertmanagerConfigNamespaceSelector (on Alertmanager) | nothing; merged into routing | covered in section 4.2 |
- Namespace selector gotchas: on the
PrometheusCR, anilnamespace selector watches only Prometheus's own namespace,{}watches all namespaces, andmatchLabelsfilters by namespace label (such askubernetes.io/metadata.name: team-a). On aServiceMonitoritself,spec.namespaceSelectoris the second gate: setmatchNames: [argocd]orany: true, because omitting it restricts discovery to the monitor's own namespace. - Free label enrichment:
jobLabelpromotes a Service label intojob, whiletargetLabelsandpodTargetLabelscopy Service or pod labels onto every scraped series. Without them, series only carrynamespace,pod,service, andendpoint, so "aggregate by team" requires copying that label here first. - Endpoints to EndpointSlice: since Kubernetes 1.33 deprecated
v1 Endpoints, modern operators supportspec.serviceDiscoveryRole: EndpointSlice(withdiscovery.k8s.io/endpointslicesRBAC). Seeing an operator log warning about deprecated Endpoints just points to that migration. - Safety limits:
sampleLimit,labelLimit,labelNameLengthLimit, andlabelValueLengthLimitabort oversized scrapes outright (showing the reason under Status → Targets), handy as a circuit breaker against runaway exporters. Always keepscrapeTimeoutshorter thanscrapeIntervalor config reload rejects it. - Relabel actions:
replace(default),keep/dropviaregexoversourceLabels,labelmap(copying__meta_kubernetes_pod_label_(.+)into real labels),labeldrop/labelkeep, andhashmod. Rewrite__address__,__scheme__, and__metrics_path__whenever using rawkubernetesSDConfigsinside aScrapeConfig.
Before authoring any monitor, run three quick reads: check the Prometheus selectors via kubectl -n monitoring get prometheus -o yaml, check the target Service's port names via kubectl get svc <name> -o jsonpath='{.spec.ports[*].name}', and confirm ready addresses via kubectl get endpointslices -l kubernetes.io/service-name=<name>. Zero guesswork.
PromQL beyond rate(), and platform tool metrics
| Function / form | Use it for | Remember |
|---|---|---|
| increase(c[1h]) | "how many in the last hour?" | extrapolated (may be fractional); equals rate × window |
| irate(c[5m]) | instantaneous slope across last two samples | great for debugging spikes, never for alerts |
| changes(g[1h]) / resets(c[1h]) | flapping detection and counter restarts | changes(kube_pod_container_status_ready[10m]) > 3 spots crash-looping fast |
| absent(x) / absent_over_time(x[10m]) | alerting when a series vanishes | emits 1 carrying the exact equality labels from your selector |
| predict_linear(g[1h], 4*3600) | forecasting disk full or cert expiry N seconds out | gauges only: predict_linear(node_filesystem_avail_bytes[6h], 24*3600) < 0 |
| label_replace(v, "dst", "$1", "src", "(.*)") | extracting or renaming labels for joins | anchored regex; use label_join to concatenate |
| topk(5, ...) / bottomk | finding top offenders | instant queries; over a range query, more than k total series can appear across timestamps |
| count by (namespace) (kube_pod_info) | counting objects | count counts series while sum adds values |
| histogram_quantile(0.99, sum by (le) (rate(b[5m]))) | classic histograms | preserve le; for native histograms drop both by (le) and _bucket |
| histogram_count(h) / histogram_sum(h) / histogram_fraction(0, 0.3, h) | native histograms | stable in Prometheus 3.8+; requires scrape_native_histograms: true (operator: scrapeNativeHistograms) |
| x offset 1w / x @ end() | comparing against last week or pinning a timestamp | offset sits right after the selector, not outside the function |
| a / on(pod) group_left(team) b | joining series with different label sets | on sets join keys; group_left pulls extra labels from the one-side onto the many-side |
| (sum(...) or vector(0)) | returning 0 instead of empty | keeps single-stat dashboard panels from showing "No data" |
Storage, cardinality, and scale
- Retention: configured via
--storage.tsdb.retention.time(15d default when neither is set) and--storage.tsdb.retention.size(exposed asspec.retentionandspec.retentionSize). Keep size limits around 80–85% of your PVC because TSDB compaction briefly spikes disk usage. - Hunting cardinality: open Status → TSDB Status or run
topk(10, count by (__name__) ({__name__=~".+"})). Fix the explosion at ingestion (metricRelabelingsdropping the noisy metric or label) and upstream in the exporter; don't just throw RAM at it. - Scaling past one Prometheus: use
remoteWrite(v2.0 in Prometheus 3.x) into Thanos Receive, Mimir, or Cortex, or pair a Thanos sidecar with object storage.PrometheusAgentruns scrape-only purely to remote-write. Federation (/federatewithhonor_labels: true) pulls aggregated rollups for small setups. Whenever a scenario asks for multi-cluster long-term retention, reach for remote write or Thanos, not federation. - Kubernetes native histograms: the
NativeHistogramsfeature gate arrived alpha in 1.36 and became beta/default-on in 1.37; on older clusters control-plane metrics still emit classic_bucketseries.
Key metrics exported by platform tools
| Tool | Key series | Scrape via |
|---|---|---|
| Argo CD | argocd_app_info{sync_status,health_status}, argocd_app_sync_total{phase}, argocd_app_reconcile, argocd_appset_info | Services *-metrics in argocd, port http-metrics |
| Flux | gotk_reconcile_duration_seconds, controller_runtime_reconcile_total{controller,result}, plus gotk_resource_info{ready,suspended,revision} (emitted via kube-state-metrics CustomResourceState, not the Flux controllers themselves) | PodMonitor on flux-system controllers, port http-prom |
| Tekton | tekton_pipelines_controller_pipelinerun_total{status}, ..._pipelinerun_duration_seconds, ..._running_pipelineruns, ..._taskrun_total | tekton-pipelines-controller Service, port 9090 |
| Crossplane | crossplane_managed_resource_ready, ..._synced, ..._first_time_to_readiness_seconds, ..._drift_seconds (providers, port 8080); core requires metrics.enabled=true | PodMonitor on provider pods, or annotations via DeploymentRuntimeConfig |
| Any CRD | kube_customresource_* generated by --custom-resource-state-config (groupVersionKind, metrics[].each.gauge.path, labelsFromPath) | kube-state-metrics plus read RBAC for that CRD |
| Kyverno / Gatekeeper | kyverno_policy_results_total{policy_validation_mode,rule_result}, kyverno_admission_review_duration_seconds; gatekeeper_violations{enforcement_action}, gatekeeper_audit_last_run_time | ServiceMonitors on their metrics Services |
"Scrape tool X and write a PromQL query showing Y" is simply your ServiceMonitor selector-and-port-name drill against a fresh Service, followed by one query from the table above. Inspect the Service and port names first; once the target flips UP, you can read every metric name straight off its /metrics endpoint or Prometheus autocomplete.
Exercises
Prometheus's UI address comes from make urls.
In the UI under Status → Targets, or via API: count the scrape pools, find which ServiceMonitor each corresponds to (kubectl -n monitoring get servicemonitors), and confirm zero targets down.
curl -s 'http://<prom>/api/v1/query?query=count(up==0)' | jq -r '.data.result[0].value[1] // "0"' prints 0. If not, the down target's job name points at the responsible ServiceMonitor.Deploy an app that exposes metrics and monitor it, first wrong, then right:
kubectl create deploy example --image=quay.io/brancz/prometheus-example-app:v0.5.0 --port=8080
kubectl expose deploy example --port=8080 --name=example
kubectl apply -f - <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata: { name: example, namespace: default }
spec:
selector: { matchLabels: { app: example } }
endpoints: [{ port: "8080" }]
EOFoutputcaptured 2026-08-26
$ kubectl create deploy example --image=quay.io/brancz/prometheus-example-app:v0.5.0 --port=8080
deployment.apps/example created
$ kubectl expose deploy example --port=8080 --name=example
service/example exposed
$ kubectl apply -f - <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata: { name: example, namespace: default }
spec:
selector: { matchLabels: { app: example } }
endpoints: [{ port: "8080" }]
EOF
servicemonitor.monitoring.coreos.com/example createdWait a minute, search Targets: nothing. The endpoint's port must be the Service's port name, and this Service has none, so the monitor matches the Service and then finds no endpoint. It fails silently. Fix it: patch the Service so the port is named (kubectl patch svc example --type=json -p '[{"op":"add","path":"/spec/ports/0/name","value":"web"}]') and set port: web in the monitor.
up{job="example"} returns 1 in the UI. Then add the release: prometheus label to your monitor anyway and confirm nothing changes here. Be able to say why it would be the difference between working and ignored on a stock install.Generate a little traffic (kubectl run curl --image=curlimages/curl:8.11.1 --restart=Never -- sh -c 'for i in $(seq 100); do curl -s example.default.svc:8080; done'), then write, without copying: the request rate (rate(http_requests_total{job="example"}[5m])), summed by status code, and the p95 duration from http_request_duration_seconds_bucket.
Answer three questions using only metrics already collected: how many pods per namespace (kube_pod_info), which container restarts most (kube_pod_container_status_restarts_total), and each node's CPU pressure (node_load1 vs allocatable).
ServiceMonitor and PodMonitor only reach things Kubernetes knows about. A ScrapeConfig is how the operator scrapes a static target, which is what you need for a switch, an appliance, or anything outside the cluster.
kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.scrapeConfigSelector}{"\n"}'
kubectl -n default create deployment fakemetrics --image=ghcr.io/stefanprodan/podinfo:6.7.1
kubectl -n default expose deployment fakemetrics --port=9898
kubectl -n default get svc fakemetrics -o jsonpath='{.spec.clusterIP}{"\n"}'
kubectl apply -f - <<'EOF'
apiVersion: monitoring.coreos.com/v1alpha1
kind: ScrapeConfig
metadata: { name: static-target, namespace: monitoring, labels: { release: prometheus } }
spec:
staticConfigs:
- targets: ["fakemetrics.default.svc.cluster.local:9898"]
labels: { source: static }
metricsPath: /metrics
scrapeInterval: 30s
EOF
sleep 90
kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
sleep 5
curl -s localhost:9090/api/v1/targets | jq '.data.activeTargets[] | select(.labels.source=="static") | {scrapeUrl, health, lastError}'
kill $PF1
kubectl delete scrapeconfig static-target -n monitoring
kubectl -n default delete deployment fakemetrics
kubectl -n default delete svc fakemetricsoutputcaptured 2026-09-12
$ kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.scrapeConfigSelector}{"\n"}'
{"matchLabels":{"release":"prometheus"}}
$ kubectl -n default create deployment fakemetrics --image=ghcr.io/stefanprodan/podinfo:6.7.1
deployment.apps/fakemetrics created
$ kubectl -n default expose deployment fakemetrics --port=9898
service/fakemetrics exposed
$ kubectl -n default get svc fakemetrics -o jsonpath='{.spec.clusterIP}{"\n"}'
10.96.20.183
$ kubectl apply -f - <<'EOF'
apiVersion: monitoring.coreos.com/v1alpha1
kind: ScrapeConfig
metadata: { name: static-target, namespace: monitoring, labels: { release: prometheus } }
spec:
staticConfigs:
- targets: ["fakemetrics.default.svc.cluster.local:9898"]
labels: { source: static }
metricsPath: /metrics
scrapeInterval: 30s
EOF
scrapeconfig.monitoring.coreos.com/static-target created
$ sleep 90
$ kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9090 -> 9090
Forwarding from [::1]:9090 -> 9090
$ curl -s localhost:9090/api/v1/targets | jq '.data.activeTargets[] | select(.labels.source=="static") | {scrapeUrl, health, lastError}'
Handling connection for 9090
{
"scrapeUrl": "http://fakemetrics.default.svc.cluster.local:9898/metrics",
"health": "up",
"lastError": ""
}
$ kill $PF1
$ kubectl delete scrapeconfig static-target -n monitoring
scrapeconfig.monitoring.coreos.com "static-target" deleted from monitoring namespace
$ kubectl -n default delete deployment fakemetrics
deployment.apps "fakemetrics" deleted from default namespace
$ kubectl -n default delete svc fakemetrics
service "fakemetrics" deleted from default namespacescrapeConfigSelector first: if it does not match your labels, the object is valid, ignored, and silent.A Probe answers "can this be reached", which is a different question from any metric the app exports. It needs blackbox-exporter, which the lab does not install, so this block installs it.
Uninstall it afterwards if you are tight on memory; leave it if you intend to write availability alerts in 4.2.
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update prometheus-community
helm upgrade --install blackbox prometheus-community/prometheus-blackbox-exporter -n monitoring --wait
kubectl apply -f - <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: Probe
metadata: { name: demo-reachable, namespace: monitoring, labels: { release: prometheus } }
spec:
interval: 30s
module: http_2xx
prober:
url: blackbox-prometheus-blackbox-exporter.monitoring.svc:9115
targets:
staticConfig:
static:
- http://prometheus-kube-prometheus-prometheus.monitoring.svc:9090/-/healthy
- http://staging-demo.team-a.svc.cluster.local
EOF
sleep 120
kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
sleep 5
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=probe_success' | jq '.data.result[] | {instance: .metric.instance, value: .value[1]}'
# Prometheus reloads its config and scrapes before any of this appears
sleep 120
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=probe_duration_seconds' | jq '.data.result[] | {instance: .metric.instance, value: .value[1]}'
kill $PF1
kubectl -n monitoring delete probe demo-reachable
helm -n monitoring uninstall blackboxoutputcaptured 2026-09-12
$ helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
"prometheus-community" already exists with the same configuration, skipping
$ helm repo update prometheus-community
Hang tight while we grab the latest from your chart repositories...
...Successfully got an update from the "prometheus-community" chart repository
Update Complete. ⎈Happy Helming!⎈
$ helm upgrade --install blackbox prometheus-community/prometheus-blackbox-exporter -n monitoring --wait
Release "blackbox" does not exist. Installing it now.
NAME: blackbox
LAST DEPLOYED: Sun Sep 13 12:44:55 2026
NAMESPACE: monitoring
STATUS: deployed
REVISION: 1
DESCRIPTION: Install complete
TEST SUITE: None
NOTES:
See https://github.com/prometheus/blackbox_exporter/ for how to configure Prometheus and the Blackbox Exporter.
1. Get the application URL by running these commands:
export POD_NAME=$(kubectl get pods --namespace monitoring -l "app.kubernetes.io/name=prometheus-blackbox-exporter,app.kubernetes.io/instance=blackbox" -o jsonpath="{.items[0].metadata.name}")
export CONTAINER_PORT=$(kubectl get pod --namespace monitoring $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}")
echo "Visit http://127.0.0.1:8080 to use your application"
kubectl --namespace monitoring port-forward $POD_NAME 8080:$CONTAINER_PORT
$ kubectl apply -f - <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: Probe
metadata: { name: demo-reachable, namespace: monitoring, labels: { release: prometheus } }
spec:
interval: 30s
module: http_2xx
prober:
url: blackbox-prometheus-blackbox-exporter.monitoring.svc:9115
targets:
staticConfig:
static:
- http://prometheus-kube-prometheus-prometheus.monitoring.svc:9090/-/healthy
- http://staging-demo.team-a.svc.cluster.local
EOF
probe.monitoring.coreos.com/demo-reachable created
$ sleep 120
$ kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9090 -> 9090
Forwarding from [::1]:9090 -> 9090
$ curl -sG localhost:9090/api/v1/query --data-urlencode 'query=probe_success' | jq '.data.result[] | {instance: .metric.instance, value: .value[1]}'
Handling connection for 9090
{
"instance": "http://prometheus-kube-prometheus-prometheus.monitoring.svc:9090/-/healthy",
"value": "1"
}
{
"instance": "http://staging-demo.team-a.svc.cluster.local",
"value": "0"
}
$ # Prometheus reloads its config and scrapes before any of this appears
$ sleep 120
$ curl -sG localhost:9090/api/v1/query --data-urlencode 'query=probe_duration_seconds' | jq '.data.result[] | {instance: .metric.instance, value: .value[1]}'
Handling connection for 9090
{
"instance": "http://prometheus-kube-prometheus-prometheus.monitoring.svc:9090/-/healthy",
"value": "0.003463362"
}
{
"instance": "http://staging-demo.team-a.svc.cluster.local",
"value": "5.002871734"
}
$ kill $PF1
$ kubectl -n monitoring delete probe demo-reachable
probe.monitoring.coreos.com "demo-reachable" deleted from monitoring namespace
$ helm -n monitoring uninstall blackbox
release "blackbox" uninstalledprobe_success returns two series. The monitoring target is 1. The team-a target is 0 with probe_duration_seconds at the 5 second module timeout, because team-a's default-deny NetworkPolicy has no rule for ingress from monitoring. A blackbox probe measures reachability from where the prober sits, which is why it disagrees with the target's own metrics.A ServiceMonitor only looks in its own namespace unless you tell it otherwise. That single omission is the most common reason a correct-looking monitor produces no targets and no error.
kubectl -n monitoring delete servicemonitor argocd-metrics --ignore-not-found
kubectl apply -f - <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata: { name: argocd-metrics, namespace: monitoring, labels: { release: prometheus } }
spec:
selector:
matchLabels: { app.kubernetes.io/name: argocd-metrics }
endpoints:
- port: http-metrics
EOF
sleep 60
kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
sleep 5
sleep 60
curl -s localhost:9090/api/v1/targets | jq '[.data.activeTargets[] | select(.scrapePool | contains("argocd-metrics"))] | length'
kubectl -n monitoring patch servicemonitor argocd-metrics --type merge -p '{"spec":{"namespaceSelector":{"matchNames":["argocd"]}}}'
sleep 60
sleep 60
curl -s localhost:9090/api/v1/targets | jq '[.data.activeTargets[] | select(.scrapePool | contains("argocd-metrics"))] | length'
kill $PF1
kubectl -n monitoring delete servicemonitor argocd-metricsoutputcaptured 2026-09-13
$ kubectl -n monitoring delete servicemonitor argocd-metrics --ignore-not-found
$ kubectl apply -f - <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata: { name: argocd-metrics, namespace: monitoring, labels: { release: prometheus } }
spec:
selector:
matchLabels: { app.kubernetes.io/name: argocd-metrics }
endpoints:
- port: http-metrics
EOF
servicemonitor.monitoring.coreos.com/argocd-metrics created
$ sleep 60
$ kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9090 -> 9090
Forwarding from [::1]:9090 -> 9090
$ sleep 60
$ curl -s localhost:9090/api/v1/targets | jq '[.data.activeTargets[] | select(.scrapePool | contains("argocd-metrics"))] | length'
Handling connection for 9090
0
$ kubectl -n monitoring patch servicemonitor argocd-metrics --type merge -p '{"spec":{"namespaceSelector":{"matchNames":["argocd"]}}}'
servicemonitor.monitoring.coreos.com/argocd-metrics patched
$ sleep 60
$ sleep 60
$ curl -s localhost:9090/api/v1/targets | jq '[.data.activeTargets[] | select(.scrapePool | contains("argocd-metrics"))] | length'
Handling connection for 9090
1
$ kill $PF1
$ kubectl -n monitoring delete servicemonitor argocd-metrics
servicemonitor.monitoring.coreos.com "argocd-metrics" deleted from monitoring namespacenamespaceSelector to your mental template for every ServiceMonitor you write in a task.A Prometheus that falls over is usually a labels problem, not a volume problem. Two queries and the TSDB status page tell you which metric and which label are responsible, which is the answer a capacity question wants.
kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
sleep 5
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=topk(10, count by (__name__) ({__name__=~".+"}))' | jq -r '.data.result[] | "\(.metric.__name__) \(.value[1])"'
curl -s localhost:9090/api/v1/status/tsdb | jq '{numSeries: .data.headStats.numSeries, numLabelPairs: .data.headStats.numLabelPairs, topSeriesCountByMetricName: .data.seriesCountByMetricName[:5]}'
curl -s localhost:9090/api/v1/status/tsdb | jq '.data.labelValueCountByLabelName[:5]'
kill $PF1outputcaptured 2026-09-12
$ kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9090 -> 9090
Forwarding from [::1]:9090 -> 9090
$ curl -sG localhost:9090/api/v1/query --data-urlencode 'query=topk(10, count by (__name__) ({__name__=~".+"}))' | jq -r '.data.result[] | "\(.metric.__name__) \(.value[1])"'
Handling connection for 9090
apiserver_request_duration_seconds_bucket 13550
apiserver_request_body_size_bytes_bucket 13472
apiserver_request_sli_duration_seconds_bucket 8224
etcd_request_duration_seconds_bucket 7560
apiserver_watch_list_duration_seconds_bucket 5760
apiserver_response_sizes_bucket 5000
apiserver_watch_cache_read_wait_seconds_bucket 3850
apiserver_watch_events_sizes_bucket 2628
kubernetes_feature_enabled 2177
apiserver_request_total 1683
$ curl -s localhost:9090/api/v1/status/tsdb | jq '{numSeries: .data.headStats.numSeries, numLabelPairs: .data.headStats.numLabelPairs, topSeriesCountByMetricName: .data.seriesCountByMetricName[:5]}'
Handling connection for 9090
{
"numSeries": 169887,
"numLabelPairs": 11365,
"topSeriesCountByMetricName": [
{
"name": "apiserver_request_duration_seconds_bucket",
"value": 13550
},
{
"name": "apiserver_request_body_size_bytes_bucket",
"value": 13472
},
{
"name": "apiserver_request_sli_duration_seconds_bucket",
"value": 8224
},
{
"name": "etcd_request_duration_seconds_bucket",
"value": 7560
},
{
"name": "apiserver_watch_list_duration_seconds_bucket",
"value": 5760
}
]
}
$ curl -s localhost:9090/api/v1/status/tsdb | jq '.data.labelValueCountByLabelName[:5]'
Handling connection for 9090
[
{
"name": "__name__",
"value": 2476
},
{
"name": "name",
"value": 1391
},
{
"name": "id",
"value": 672
},
{
"name": "resource",
"value": 618
},
{
"name": "le",
"value": 415
}
]
$ kill $PF1Two functions carry more exam weight than their length suggests. One extrapolates a trend into the future, the other alerts on a series that stopped existing, which is the failure a threshold can never catch.
kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
sleep 5
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=count by (mountpoint,fstype) (node_filesystem_avail_bytes)' | jq -r '.data.result[] | "\(.metric.mountpoint) \(.metric.fstype)"'
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=predict_linear(node_filesystem_avail_bytes[1h], 24*3600)' | jq '[.data.result[] | {instance: .metric.instance, mountpoint: .metric.mountpoint, predicted: .value[1]}] | .[0:3]'
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=absent_over_time(up{job="does-not-exist"}[5m])' | jq '.data.result'
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=absent_over_time(up{job="kubelet"}[5m])' | jq '.data.result'
kill $PF1outputcaptured 2026-09-13
$ kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9090 -> 9090
Forwarding from [::1]:9090 -> 9090
$ curl -sG localhost:9090/api/v1/query --data-urlencode 'query=count by (mountpoint,fstype) (node_filesystem_avail_bytes)' | jq -r '.data.result[] | "\(.metric.mountpoint) \(.metric.fstype)"'
Handling connection for 9090
/etc/hostname btrfs
/etc/hosts btrfs
/etc/kubernetes/audit btrfs
/etc/resolv.conf btrfs
/usr/lib/modules btrfs
/var btrfs
/run tmpfs
/run/credentials/systemd-journald.service tmpfs
/tmp tmpfs
$ curl -sG localhost:9090/api/v1/query --data-urlencode 'query=predict_linear(node_filesystem_avail_bytes[1h], 24*3600)' | jq '[.data.result[] | {instance: .metric.instance, mountpoint: .metric.mountpoint, predicted: .value[1]}] | .[0:3]'
Handling connection for 9090
[
{
"instance": "172.18.0.4:9100",
"mountpoint": "/etc/hostname",
"predicted": "907166223218.7759"
},
{
"instance": "172.18.0.4:9100",
"mountpoint": "/etc/hosts",
"predicted": "907166223218.7759"
},
{
"instance": "172.18.0.4:9100",
"mountpoint": "/etc/kubernetes/audit",
"predicted": "907166223218.7759"
}
]
$ curl -sG localhost:9090/api/v1/query --data-urlencode 'query=absent_over_time(up{job="does-not-exist"}[5m])' | jq '.data.result'
Handling connection for 9090
[
{
"metric": {
"job": "does-not-exist"
},
"value": [
1789306067.750,
"1"
]
}
]
$ curl -sG localhost:9090/api/v1/query --data-urlencode 'query=absent_over_time(up{job="kubelet"}[5m])' | jq '.data.result'
Handling connection for 9090
[]
$ kill $PF1/ is not among them, because a kind node's root is an overlay mount and node-exporter excludes overlay by filesystem type, so the usual mountpoint="/" selector matches nothing and predict_linear over it returns nothing rather than an error. The second query returns one predicted number per filesystem that does exist, and absent_over_time returns a series for the job that does not exist and nothing for the one that does. That inversion is the whole idea: the alert fires when the query has a result.Retention is two numbers and whichever binds first wins. On a cluster you inherit, read them before you promise anyone a month of history.
kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.retention} {.items[0].spec.retentionSize}{"\n"}'
kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.storage}' | jq
kubectl -n monitoring get pvc -l app.kubernetes.io/name=prometheus -o custom-columns=NAME:.metadata.name,CAPACITY:.status.capacity.storage,CLASS:.spec.storageClassName
kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
sleep 5
curl -s localhost:9090/api/v1/status/runtimeinfo | jq '.data | {storageRetention, corruptionCount, timeSeriesCount}'
kill $PF1outputcaptured 2026-09-12
$ kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.retention} {.items[0].spec.retentionSize}{"\n"}'
6h
$ kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.storage}' | jq
$ kubectl -n monitoring get pvc -l app.kubernetes.io/name=prometheus -o custom-columns=NAME:.metadata.name,CAPACITY:.status.capacity.storage,CLASS:.spec.storageClassName
NAME CAPACITY CLASS
$ kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9090 -> 9090
Forwarding from [::1]:9090 -> 9090
$ curl -s localhost:9090/api/v1/status/runtimeinfo | jq '.data | {storageRetention, corruptionCount, timeSeriesCount}'
Handling connection for 9090
{
"storageRetention": "6h",
"corruptionCount": 0,
"timeSeriesCount": null
}
$ kill $PF1Flux and Tekton both export metrics that answer delivery questions rather than infrastructure ones. Wiring them is two objects, and the queries afterwards are the raw material for section 4.5.
kubectl apply -f - <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata: { name: flux-controllers, namespace: monitoring, labels: { release: prometheus } }
spec:
namespaceSelector: { matchNames: [flux-system] }
selector:
matchExpressions:
- { key: app, operator: Exists }
podMetricsEndpoints:
- port: http-prom
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata: { name: tekton-controller, namespace: monitoring, labels: { release: prometheus } }
spec:
namespaceSelector: { matchNames: [tekton-pipelines] }
selector:
matchLabels: { app: tekton-pipelines-controller }
endpoints:
- port: http-metrics
EOF
sleep 90
kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
sleep 5
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=gotk_reconcile_duration_seconds_count' | jq '.data.result | length'
curl -sG localhost:9090/api/v1/query --data-urlencode 'query=tekton_pipelines_controller_pipelinerun_total' | jq '.data.result[] | {status: .metric.status, value: .value[1]}'
kill $PF1outputcaptured 2026-09-12
$ kubectl apply -f - <<'EOF'
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata: { name: flux-controllers, namespace: monitoring, labels: { release: prometheus } }
spec:
namespaceSelector: { matchNames: [flux-system] }
selector:
matchExpressions:
- { key: app, operator: Exists }
podMetricsEndpoints:
- port: http-prom
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata: { name: tekton-controller, namespace: monitoring, labels: { release: prometheus } }
spec:
namespaceSelector: { matchNames: [tekton-pipelines] }
selector:
matchLabels: { app: tekton-pipelines-controller }
endpoints:
- port: http-metrics
EOF
podmonitor.monitoring.coreos.com/flux-controllers created
servicemonitor.monitoring.coreos.com/tekton-controller created
$ sleep 90
$ kubectl -n monitoring port-forward svc/prometheus-kube-prometheus-prometheus 9090:9090 & PF1=$!
$ sleep 5
Forwarding from 127.0.0.1:9090 -> 9090
Forwarding from [::1]:9090 -> 9090
$ curl -sG localhost:9090/api/v1/query --data-urlencode 'query=gotk_reconcile_duration_seconds_count' | jq '.data.result | length'
Handling connection for 9090
8
$ curl -sG localhost:9090/api/v1/query --data-urlencode 'query=tekton_pipelines_controller_pipelinerun_total' | jq '.data.result[] | {status: .metric.status, value: .value[1]}'
Handling connection for 9090
{
"status": "success",
"value": "1"
}
$ kill $PF1Self-check
Your ServiceMonitor is correct and no target appears. List the checks in order.
1) Prometheus's serviceMonitorSelector and serviceMonitorNamespaceSelector: is Prometheus even watching your monitor? 2) Does the monitor's selector match the Service's labels (and its namespaceSelector match the Service's namespace)? 3) Is endpoints[].port the Service's port name? 4) Does the Service have ready endpoints? 5) Check RBAC and NetworkPolicy between monitoring and the target namespace.
Why is sum(rate(x[5m])) right and rate(sum(x)[5m]) wrong?
Counter resets happen independently per series, and rate() only knows how to compensate for resets on an individual series. Summing first mixes resets across pods into garbage (and isn't even valid syntax without a subquery). Always rate() first, aggregate second.
How do you alert on "the metric disappeared entirely"?
Use absent(up{job="x"} == 1) or absent(metric). Standard comparisons return empty when there's no data to compare, so they can never fire; absent() explicitly turns "no series" into 1.
A p95 query returns NaN. Two plausible reasons?
Either no requests landed in the lookback window (empty buckets), or your aggregation accidentally dropped the le label that histogram_quantile needs. Keep it intact with histogram_quantile(0.95, sum by (le) (rate(x_bucket[5m]))).
An exporter added a label with one value per request. What happens, and what is the fix?
Instant cardinality explosion: every request creates a brand-new series, blowing up TSDB memory and slowing queries to a crawl. Drop the label or metric immediately via metricRelabelings, then strip it from the exporter. High-cardinality IDs belong in logs and traces, never Prometheus labels.
You need to scrape a database VM outside the cluster with the Prometheus Operator, without editing the Prometheus config by hand. Which CRD, and which selector must match?
Use a ScrapeConfig with staticConfigs[].targets: ["db.example.internal:9187"] (or httpSDConfigs / dnsSDConfigs), labeled to match Prometheus's scrapeConfigSelector and placed in a namespace matched by scrapeConfigNamespaceSelector (or Prometheus's own namespace if that selector is nil).
Predict that a volume fills within a day, and alert if any series that should exist has vanished. Two expressions?
For disk fill: predict_linear(node_filesystem_avail_bytes{mountpoint="/data"}[6h], 24*3600) < 0. For a vanished target: absent_over_time(up{job="payments"}[10m]), which evaluates to 1 only when zero samples showed up during the entire 10-minute window.
A ServiceMonitor in monitoring selects the right labels and port for Services in argocd, yet no target appears and Prometheus's own selectors are {}. What is missing?
spec.namespaceSelector on the ServiceMonitor itself (matchNames: [argocd] or any: true). Left unset, a ServiceMonitor only looks in its own namespace. Remember the two-hop rule: Prometheus's selector discovers monitors, and the monitor's namespaceSelector discovers Services.
Docs to know your way around
- prometheus.io: querying basics and the function reference (
rate,increase,histogram_quantile,absent); metric types. - prometheus-operator.dev: the ServiceMonitor troubleshooting page, which is the release-label story in official form; the API reference for ServiceMonitor/PodMonitor/ScrapeConfig.
- Offline:
kubectl explain servicemonitor.spec.endpoints, the Prometheus UI's Status → Targets and Status → Configuration pages, and its built-in expression autocompletion. - prometheus-operator.dev/docs/developer/scrapeconfig: the ScrapeConfig page with the selector and namespace rules; the API reference's
ServiceMonitorsection listsjobLabel,targetLabels, the limits andserviceDiscoveryRole. - prometheus.io/docs/prometheus/latest/querying/functions:
predict_linear,absent_over_time,label_replace, and the native-histogram functions; /storage for the retention flags. - argo-cd.readthedocs.io/en/stable/operator-manual/metrics, fluxcd.io/flux/monitoring/metrics, tekton.dev/docs/pipelines/metrics, docs.crossplane.io/latest/guides/metrics: the metric-name tables, one page each.