Monitoring Kubernetes
Install kube-prometheus-stack with Helm, scrape your app with a ServiceMonitor, and write the PromQL for cluster health and pod health: restarts, OOM kills and throttling.
By the end of this lesson you'll be able to
0 of 5 completeOn Kubernetes, pods come and go every deploy, so a hand-written target list can't keep up, and there are new questions: are all replicas running, was a pod OOM-killed, is the cluster out of room? In this lesson you'll install kube-prometheus-stack, scrape your own app with a ServiceMonitor, and write the PromQL for cluster and pod health.
The lab machine for this course had no Kubernetes cluster, so the commands and manifests below are shown without their output. They follow the chart's and the Prometheus Operator's current documentation, linked in Resources. Run them on kind, minikube or k3d to see the output yourself.
kube-prometheus-stack
The chart installs:
| Piece | Runs as | Collects |
|---|---|---|
| Prometheus Operator | Deployment | Nothing itself; manages Prometheus and Alertmanager from custom resources |
| Prometheus | StatefulSet | Scrapes everything below, evaluates rules |
| Alertmanager | StatefulSet | Routes alerts (lesson 4) |
| Grafana | Deployment | Ready-made Kubernetes dashboards |
| node-exporter | DaemonSet (one pod per node) | Node CPU, memory, disk, network (lesson 2) |
| kube-state-metrics | Deployment | The state of Kubernetes objects: replicas, pod phase, restarts, requests and limits |
| kubelet / cAdvisor | Already on every node | Actual CPU, memory and network usage per container |
It also ships about a hundred recording and alert rules from the kubernetes-mixin project, with
alerts such as KubePodCrashLooping, KubeDeploymentReplicasMismatch, KubeNodeNotReady,
KubeCPUOvercommit and the always-firing Watchdog from lesson 4. Each alert has a runbook at
runbooks.prometheus-operator.dev.
Install it
$ helm repo add prometheus-community https://prometheus-community.github.io/helm-charts $ helm repo update $ helm install monitoring prometheus-community/kube-prometheus-stack \ --namespace monitoring --create-namespace $ kubectl get pods -n monitoring
kubectl get pods -n monitoringkubectltalk to a Kubernetes clustergetlist objects-nin this namespace
The release name (monitoring) matters later: the chart labels its objects with
release: monitoring. After a minute or two you should see pods for the operator, Prometheus,
Alertmanager, Grafana, kube-state-metrics, and one node-exporter per node.
The UIs aren't exposed outside the cluster. Reach them with port-forward:
$ kubectl port-forward -n monitoring svc/monitoring-kube-prometheus-prometheus 9090 $ kubectl port-forward -n monitoring svc/monitoring-grafana 3000:80 $ kubectl get secret -n monitoring monitoring-grafana \ -o jsonpath="{.data.admin-password}" | base64 -d; echo
kubectl port-forward -n monitoring svc/monitoring-kube-prometheus-prometheus 9090kubectltalk to a Kubernetes cluster-nin this namespace
kubectl get secret -n monitoring monitoring-grafana \getlist objects
Service names start with the release name, so with a different release name they change. List
them with kubectl get svc -n monitoring. The last command prints Grafana's generated admin
password; log in as admin.
Scrape your own app with a ServiceMonitor
Your app exposes /metrics on a port named metrics, behind a Service labelled app: api. Tell
the Operator to scrape it:
# servicemonitor.yaml apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: api namespace: shop labels: release: monitoring # so this stack's Prometheus picks it up spec: selector: matchLabels: app: api # Services with this label namespaceSelector: matchNames: [shop] endpoints: - port: metrics # the Service port's *name*, not its number path: /metrics interval: 30s
What happens after kubectl apply -f servicemonitor.yaml:
- The Operator sees the new ServiceMonitor and checks it matches the Prometheus resource's
serviceMonitorSelector(by default in this chart: the labelrelease: monitoring). - It writes a scrape job into Prometheus's config that uses Kubernetes service discovery.
- Prometheus finds the Service, follows it to every ready pod behind it, and scrapes each pod.
- New pods are picked up on the next discovery refresh, with labels like
namespace,podandserviceadded automatically.
If the app doesn't appear on Status → Target health, it's almost always one of three things:
the release label is missing, the selector doesn't match the Service's labels, or port uses a
number or a name the Service doesn't have. A PodMonitor does the same for pods without a Service,
and a PrometheusRule object adds alert rules the same way.
Cluster metrics
Cluster metrics answer "is the platform healthy?": nodes, capacity and the control plane.
# Nodes that are not Ready kube_node_status_condition{condition="Ready", status="true"} == 0 # Share of the cluster's allocatable CPU that pods have requested sum(kube_pod_container_resource_requests{resource="cpu"}) / sum(kube_node_status_allocatable{resource="cpu"}) # Deployments missing replicas kube_deployment_spec_replicas != kube_deployment_status_replicas_available # Pods stuck waiting to be scheduled sum by (namespace) (kube_pod_status_phase{phase="Pending"})
The second query is worth understanding. The scheduler places pods by their requests, not by
real usage. When requested CPU nears 100% of allocatable, new pods stay Pending even if the nodes
look idle on a CPU graph. That's when you add nodes, or lower over-sized requests.
Pod metrics
Pod metrics answer "is my app healthy?". These come from two places: cAdvisor (real usage,
container_*) and kube-state-metrics (state, kube_pod_*).
# CPU cores each pod is using sum by (namespace, pod) (rate(container_cpu_usage_seconds_total{container!=""}[5m])) # Memory each pod is really using (what the OOM killer looks at) sum by (namespace, pod) (container_memory_working_set_bytes{container!=""}) # Containers that restarted in the last hour increase(kube_pod_container_status_restarts_total[1h]) > 0 # Containers whose last restart was an OOM kill kube_pod_container_status_last_terminated_reason{reason="OOMKilled"} == 1 # Share of CPU periods in which the container was throttled by its limit sum by (namespace, pod) (rate(container_cpu_cfs_throttled_periods_total[5m])) / sum by (namespace, pod) (rate(container_cpu_cfs_periods_total[5m]))
container!="" drops cAdvisor's extra per-pod summary series, which would otherwise be counted
twice.
Three signs to know by heart:
- Restarts climbing means a crash loop or failing liveness probe. Check
kubectl describe podand the logs (lesson 5). OOMKilledmeans memory use hit the memory limit and the kernel killed the container. Raise the limit or fix the leak, usingcontainer_memory_working_set_bytesover a week to choose.- Throttling above about 25% means the CPU limit is too low for the app's bursts. Latency goes up while average CPU looks fine, because the average hides the moments it hit the ceiling.
The ready-made Grafana dashboard Kubernetes / Compute Resources / Namespace (Pods) shows usage next to requests and limits for every pod, the fastest way to spot a pod sized wrongly.
kubectl top pods needs metrics-server, a small component that keeps only the latest values for
the autoscaler and kubectl top. It isn't part of kube-prometheus-stack and keeps no history.
Use it for "right now", and Prometheus for anything over time.
Give Prometheus persistent storage (prometheus.prometheusSpec.storageSpec in the chart values),
keep your values file in Git, and pin the chart version. For several clusters, run one Prometheus
per cluster with an external_labels cluster name and send data to central long-term storage
(Thanos, Mimir or a managed service). Watch the cardinality of your own app labels: one Prometheus
per cluster still has a memory limit.
Make Prometheus scrape your app
On a test cluster with kube-prometheus-stack installed, deploy any app that serves /metrics (or the HotROD image from the tracing lesson, which serves it on port 8080), give its Service a port named metrics, write a ServiceMonitor, and prove the target is UP. Then find the app's restarts and memory with PromQL.
servicemonitor.yamlReveal one safe solution
$ kubectl apply -f servicemonitor.yaml $ kubectl get servicemonitor -n shop $ kubectl port-forward -n monitoring svc/monitoring-kube-prometheus-prometheus 9090 $ # open http://localhost:9090/targets and look for serviceMonitor/shop/api
kubectl apply -f servicemonitor.yamlkubectltalk to a Kubernetes clusterapplycreate or update from a file-ffrom this file
kubectl get servicemonitor -n shopgetlist objects-nin this namespace
Then query kube_pod_container_status_restarts_total{namespace="shop"} and
container_memory_working_set_bytes{namespace="shop", container!=""}. If the target is missing,
check the three usual causes in order: the release: monitoring label, the selector, the port name.
Try it yourself
0 of 6 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
Which component tells you a Deployment wants 3 replicas but only 2 are available?
Official reading for this lesson
- Toolkube-prometheus-stack Helm chartprometheus-community on GitHub
- DocsPrometheus Operator getting startedPrometheus Operator
- DocsServiceMonitor API referencePrometheus Operator
- Docskube-state-metrics exposed metricsKubernetes on GitHub
- DocsResource metrics pipeline (metrics-server, kubectl top)Kubernetes
- Guidekube-prometheus runbooks for the built-in alertsPrometheus Operator
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.