# 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.

Course: [Monitoring](https://devops.rajeev.pro/courses/monitoring), lesson 7. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/monitoring/07-monitoring-kubernetes

## What you will learn

- Name the parts of kube-prometheus-stack and what each one collects
- Install the stack with Helm and open Prometheus and Grafana with port-forward
- Scrape your own app with a ServiceMonitor, and fix the most common reason it is ignored
- Tell kube-state-metrics, cAdvisor and node-exporter metrics apart
- Write PromQL for cluster health and pod health, including restarts, OOM kills and CPU throttling

On 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.

> **What was and wasn't run for this lesson.** 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.

> **Video.** [Setup Prometheus Monitoring on Kubernetes using Helm and Prometheus Operator](https://www.youtube.com/watch?v=QoDqxm7ybLc) (TechWorld with Nana)

## kube-prometheus-stack

> **Figure.** At the top, the Prometheus Operator turns ServiceMonitor, PodMonitor and PrometheusRule objects into Prometheus config. Four sources feed Prometheus: node-exporter as a DaemonSet with one pod per node for node CPU, memory and disk; kube-state-metrics reading the API server for replicas, restarts and pod phase; kubelet and cAdvisor built into every node for CPU and memory per container; and your app found by a ServiceMonitor for requests, errors and latency. Prometheus runs about 100 built-in rules, feeds Grafana with over 20 dashboards for cluster, namespace, pod and node, and sends alerts such as KubePodCrashLooping and KubeNodeNotReady to Alertmanager.
>
> kube-state-metrics says what Kubernetes thinks. cAdvisor says what the container actually uses.

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

```sh
$ 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
```

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:

```sh
$ 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
```

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:

```yaml
# 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`:

1. The Operator sees the new ServiceMonitor and checks it matches the Prometheus resource's
   `serviceMonitorSelector` (by default in this chart: the label `release: monitoring`).
2. It writes a scrape job into Prometheus's config that uses Kubernetes service discovery.
3. Prometheus finds the Service, follows it to every ready pod behind it, and scrapes each pod.
4. New pods are picked up on the next discovery refresh, with labels like `namespace`, `pod` and
   `service` added 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.

```promql
# 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_*`).

```promql
# 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:

1. **Restarts climbing** means a crash loop or failing liveness probe. Check `kubectl describe pod`
   and the logs (lesson 5).
2. **`OOMKilled`** means memory use hit the memory limit and the kernel killed the container. Raise
   the limit or fix the leak, using `container_memory_working_set_bytes` over a week to choose.
3. **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 is a different pipeline.** `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.

> **In production.** 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.

## Mission: 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.

- You need: A kind, minikube or k3d cluster with kube-prometheus-stack
- You'll have: servicemonitor.yaml

```sh
$ 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
```

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

- Add the prometheus-community Helm repo and run `helm show values prometheus-community/kube-prometheus-stack | head -50`.
- Install the stack into a `monitoring` namespace on a test cluster (kind, minikube or k3d).
- Port-forward Grafana and open the "Kubernetes / Compute Resources / Namespace (Pods)" dashboard.
- Run `kube_pod_container_status_restarts_total` in Prometheus and find the pod that restarted most.
- Create a ServiceMonitor for an app and confirm it appears on the Targets page.
- Do the mini mission and keep `servicemonitor.yaml`.

## Quiz

1. Which component tells you a Deployment wants 3 replicas but only 2 are available?
   - node-exporter
   - **kube-state-metrics** (answer)
   - cAdvisor
   Why: kube-state-metrics reads objects from the Kubernetes API and turns their state into metrics, such as kube_deployment_spec_replicas and kube_deployment_status_replicas_available.

2. Which metric shows how much memory a container is actually using right now?
   - kube_pod_container_resource_requests
   - **container_memory_working_set_bytes** (answer)
   - node_memory_MemTotal_bytes
   Why: container_memory_working_set_bytes comes from cAdvisor in the kubelet and is what the OOM killer compares with the memory limit. Requests are what the pod asked for, not what it uses.

3. You created a ServiceMonitor, but your app never shows up on the Targets page. What's the most common cause?
   - The app has no CPU limit
   - **The ServiceMonitor lacks the label the Prometheus resource selects, such as release=monitoring, or its selector doesn't match the Service's labels** (answer)
   - ServiceMonitors only work in the default namespace
   Why: The Prometheus Operator only picks up ServiceMonitors matching its serviceMonitorSelector, and each ServiceMonitor only finds Services matching its own selector and port name.

4. What does a high rate of container_cpu_cfs_throttled_periods_total mean?
   - The node is out of memory
   - **The container keeps hitting its CPU limit and is being slowed down** (answer)
   - The pod is crash-looping
   Why: When a container uses its full CPU limit in a scheduling period, the kernel throttles it until the next period. Users feel this as latency even when average CPU looks fine.

5. What does the Prometheus Operator do?
   - It replaces Prometheus with a faster database
   - **It watches custom resources such as ServiceMonitor and PrometheusRule and turns them into Prometheus configuration** (answer)
   - It installs node-exporter on laptops
   Why: Instead of editing prometheus.yml, teams create Kubernetes objects next to their apps, and the Operator keeps Prometheus's scrape config and rules in sync with them.

## Resources

- [kube-prometheus-stack Helm chart](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack) (prometheus-community on GitHub)
- [Prometheus Operator getting started](https://prometheus-operator.dev/docs/getting-started/introduction/) (Prometheus Operator)
- [ServiceMonitor API reference](https://prometheus-operator.dev/docs/api-reference/api/#monitoring.coreos.com/v1.ServiceMonitor) (Prometheus Operator)
- [kube-state-metrics exposed metrics](https://github.com/kubernetes/kube-state-metrics/tree/main/docs) (Kubernetes on GitHub)
- [Resource metrics pipeline (metrics-server, kubectl top)](https://kubernetes.io/docs/tasks/debug/debug-cluster/resource-metrics-pipeline/) (Kubernetes)
- [kube-prometheus runbooks for the built-in alerts](https://runbooks.prometheus-operator.dev/) (Prometheus Operator)
