# Monitoring, logging and troubleshooting

Read what your cluster is telling you: Pod logs, events and describe, metrics from metrics-server, and a field guide to the failures you will meet, each reproduced for real.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 9. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/09-monitoring-logging

## What you will learn

- Read container logs, including from the previous crashed container
- Use describe and events to find why a Pod isn't running
- Read CPU and memory with kubectl top and the metrics API
- Diagnose CrashLoopBackOff, ImagePullBackOff, Pending Pods and a PVC that won't bind
- Know where full monitoring (Prometheus, Grafana, traces) fits

> **Lab status.** **Verified lab:** logs, a real CrashLoopBackOff, ImagePullBackOff, a Pending PVC, kubectl top and the metrics API, all on the course's EKS cluster. The output shown is real. <br />**Code walkthrough:** the Prometheus, Grafana and tracing stack, covered by the Monitoring course. <br />**Cloud lab:** none needed; works on kind.

Things break, and Kubernetes is good at telling you why, if you know where to look. There are three places:
**logs** (what the app said), **describe and events** (what Kubernetes did), and **metrics** (how much it
used). This lesson uses each, then works through the failures you'll meet most, all reproduced for real.

## Logs

The kubelet captures each container's stdout and stderr. `kubectl logs` reads them:

```text
$ kubectl logs shop-web-55d49ccc4b-5xkmp --tail=5
10.42.0.115 GET /healthz 200
10.42.0.115 GET /healthz 200
10.42.0.115 GET /healthz 200
10.42.12.113 GET /healthz 200
10.42.0.115 GET /healthz 200
$ kubectl logs deployment/shop-web --tail=3 --timestamps
Found 3 pods, using pod/shop-web-55d49ccc4b-vrdz4
2026-11-09T06:09:23.283659765Z 10.42.28.149 GET /healthz 200
2026-11-09T06:09:23.559424501Z 10.42.12.113 GET /healthz 200
2026-11-09T06:09:28.283930705Z 10.42.28.149 GET /healthz 200
```

Those requests are the readiness and liveness probes from the kubelet (`10.42.0.115` and `10.42.28.149` are
the node IPs) and the ALB health checks. Note that `logs deployment/...` reads **one** Pod; use `-l app=shop-web
--prefix` for all of them. Logs on a node are rotated and deleted with the Pod, so production ships them to a
central store (the Monitoring course uses Loki).

> **Figure.** A node, ip-10-42-0-115, holds the Pod shop-web-55d49ccc4b-5xkmp. 1: the web container prints GET /healthz 200 to stdout. 2: containerd, the container runtime, writes each line to a file under /var/log/pods/, one folder per Pod and container. 3: when you run kubectl logs, the API server asks the kubelet on that node, which reads the file. 4: a log collector DaemonSet such as Fluent Bit or Grafana Alloy tails the same files on every node and ships them to a central store such as Loki or CloudWatch, where they survive the Pod being deleted.
>
> kubectl logs reads a file on one node. A collector copies the same file off the node before it is rotated or deleted.

## A field guide to failures

> **Figure.** A decision tree. The root says: Pod not working, run kubectl get pod and read STATUS. Five branches. Pending: look at kubectl describe events for FailedScheduling; causes are insufficient CPU or memory, an untolerated taint or unmatched selector, or an unbound PVC. ImagePullBackOff: look at the events for Failed to pull image; NotFound means a wrong tag, other causes are a wrong registry or no pull permission. CrashLoopBackOff: look at kubectl logs and the exit code; exit 1 is an app error such as DATABASE_URL is not set, or a failing liveness probe. OOMKilled: describe shows Last State Terminated, Reason OOMKilled, exit code 137; the memory limit is too low or the app leaks. Running but 0/1 Ready: describe shows the readiness probe failing; the Service sends it no traffic and its endpoints are empty.
>
> Each STATUS points to one place to look. The sections below reproduce the first three for real.

### CrashLoopBackOff: the app keeps exiting

The broken image exits on start, the way an app does when it's missing a setting:

```text
$ kubectl run broken --image=626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v3-broken
pod/broken created
$ kubectl get pod broken
NAME     READY   STATUS   RESTARTS      AGE
broken   0/1     Error    3 (35s ago)   49s
$ kubectl logs broken
config error: DATABASE_URL is not set
```

The log gives the cause straight away. `describe` adds what Kubernetes saw:

```text
$ kubectl describe pod broken | sed -n '/State:/,/Restart Count/p;/Events:/,$p'
    State:          Terminated
      Reason:       Error
      Exit Code:    1
    ...
    Restart Count:  3
Events:
  Type     Reason     Age                From               Message
  ----     ------     ----               ----               -------
  Normal   Scheduled  62s                default-scheduler  Successfully assigned default/broken to ip-10-42-0-115.ap-south-1.compute.internal
  Normal   Pulled     61s                kubelet            spec.containers{broken}: Successfully pulled image "...shop-web:v3-broken" in ...
  Normal   Started    21s (x4 over 61s)  kubelet            spec.containers{broken}: Container started
  Warning  BackOff    20s (x4 over 59s)  kubelet            spec.containers{broken}: Back-off restarting failed container broken in pod broken_default(...)
```

The image pulled fine and the container started four times; each time it exited with code 1, and the kubelet
waits longer between restarts (10s, 20s, 40s... up to 5 minutes). That growing wait is the "back-off". Reading
the exit code: **1** is the app's own error, **137** is a kill (often OOM, lesson 7), **143** is a normal
shutdown signal.

`kubectl logs broken --previous` reads the container that ran before the current one. In the lab it failed
with `unable to retrieve container logs`: with a container this short-lived, the previous one was already
cleaned up. If `--previous` is empty, the current container's log usually tells the same story.

### ImagePullBackOff: the image can't be pulled

A typo in the tag:

```text
$ kubectl create deployment typo --image=626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v9
$ kubectl get pods -l app=typo
typo-7b957fcd7c-vvmv8   0/1     ImagePullBackOff   0          46s
$ kubectl describe pod typo-7b957fcd7c-vvmv8 | sed -n '/Events:/,$p'
  Warning  Failed     24s (x2 over 51s)  kubelet            spec.containers{shop-web}: Error: ImagePullBackOff
  Warning  Failed     13s (x3 over 52s)  kubelet            spec.containers{shop-web}: Failed to pull image "...shop-web:v9": rpc error: code = NotFound desc ...
  Warning  Failed     13s (x3 over 52s)  kubelet            spec.containers{shop-web}: Error: ErrImagePull
```

`NotFound` means the tag doesn't exist. Other causes look similar with different messages: a wrong registry
name, or no permission to pull (on EKS, check the node role; elsewhere, the imagePullSecret).

### Pending Pod: nowhere to run

From the autoscaling lesson, Pods asking for more CPU than the nodes had free:

```text
  Warning  FailedScheduling  7s (x2 over 30s)  default-scheduler  0/2 nodes are available: 2 Insufficient cpu. preemption: 0/2 nodes are available: 2 No preemption victims found for incoming pod.
```

`Pending` means the scheduler hasn't placed the Pod. Its events always say why: not enough CPU or memory
(requests, lesson 7), no node matching a selector or toleration (lesson 11), or a volume that can't be bound.

### PVC stuck Pending: no storage

A claim naming a StorageClass that doesn't exist:

```text
$ kubectl get pvc orphan
orphan   Pending                                      fast-ssd       <unset>                 14s
$ kubectl describe pvc orphan | sed -n '/Events:/,$p'
  Warning  ProvisioningFailed  3s (x3 over 19s)  persistentvolume-controller  storageclass.storage.k8s.io "fast-ssd" not found
```

Any Pod using this claim stays Pending too. `kubectl get storageclass` shows what exists (lesson 12).

### The checklist

| Symptom                 | Look at                              | Usual cause                                              |
| ----------------------- | ------------------------------------ | -------------------------------------------------------- |
| CrashLoopBackOff        | `logs`, `logs --previous`, exit code | App error, missing config, failing liveness probe        |
| ImagePullBackOff        | Pod events                           | Wrong tag or registry, no pull permission                |
| Pending                 | Pod events                           | Not enough CPU or memory, selector or taint, unbound PVC |
| Running, not Ready      | Readiness probe in `describe`        | App not answering the probe path                         |
| OOMKilled, exit 137     | `describe`, `top`                    | Memory limit too low or a leak                           |
| Service returns nothing | `get endpointslices`                 | Selector matches no ready Pods                           |

`kubectl get events -A --sort-by=.lastTimestamp` is the fastest overview of everything going wrong in a cluster.

## Metrics

**metrics-server** (installed as an EKS add-on in lesson 3) collects CPU and memory from every kubelet:

```text
$ kubectl top pods -l app=shop-web --containers
POD                         NAME   CPU(cores)   MEMORY(bytes)
shop-web-55d49ccc4b-5xkmp   web    1m           11Mi
shop-web-55d49ccc4b-mp85d   web    1m           11Mi
shop-web-55d49ccc4b-vrdz4   web    1m           11Mi
```

The same data is an API (`kubectl get --raw /apis/metrics.k8s.io/v1beta1/nodes`), and it's what the Horizontal
Pod Autoscaler reads in the next lesson. metrics-server keeps only the latest values, no history.

> **Figure.** Two lanes. Top lane, right now: on every node the kubelet measures container CPU and memory; metrics-server scrapes every kubelet about every 15 seconds and keeps only the latest values; it serves the Metrics API, metrics.k8s.io; kubectl top, the Horizontal Pod Autoscaler and the Vertical Pod Autoscaler read it. The lab: kubectl top showed each shop-web Pod at 1m CPU and 11Mi memory. Bottom lane, history: node-exporter, kube-state-metrics and the kubelet expose /metrics; Prometheus scrapes and stores them as time series; Grafana draws dashboards and Alertmanager sends alerts.
>
> Top lane: built in, latest values only. Bottom lane: the history you need for dashboards and alerts.

## The full picture

`kubectl` answers "what's happening right now". For history, alerts and dashboards, clusters run the stack
from the Monitoring course: **Prometheus** with kube-state-metrics and node-exporter (usually through the
kube-prometheus-stack Helm chart), **Grafana** dashboards, **Loki** for logs, and **OpenTelemetry** with Jaeger
or Tempo for **traces** of requests across services. On EKS, CloudWatch Container Insights is the managed
alternative.

## Mission: Diagnose three broken Pods

Start a Pod from the v3-broken image, a Deployment with a non-existent tag, and a PVC with a StorageClass that doesn't exist. For each, record the status, the one line from logs or events that explains it, and the fix.

- You need: The shop-web images and a running cluster
- You'll have: ~/debug.txt

```sh
$ kubectl run broken --image=<registry>/shop-web:v3-broken
$ kubectl create deployment typo --image=<registry>/shop-web:v9
$ kubectl apply -f orphan-pvc.yaml     # storageClassName: fast-ssd
$ sleep 45; kubectl get pods,pvc > ~/debug.txt
$ kubectl logs broken >> ~/debug.txt
$ kubectl get events --sort-by=.lastTimestamp | grep -E "Failed|ProvisioningFailed" >> ~/debug.txt
$ kubectl delete pod broken; kubectl delete deployment typo; kubectl delete pvc orphan
```

Expect `CrashLoopBackOff` or `Error` with "DATABASE_URL is not set", `ImagePullBackOff` with NotFound, and a
`Pending` PVC with "fast-ssd not found".

## Try it

- Run `kubectl logs deployment/shop-web --tail=3 --timestamps`.
- Start a Pod from the broken image and watch it go to CrashLoopBackOff.
- Read its logs, its describe output and its events.
- Create a Deployment with a tag that doesn't exist and find ErrImagePull in the events.
- Do the mini mission and keep `~/debug.txt`.

## Quiz

1. A Pod is in CrashLoopBackOff. What's the first thing to look at?
   - The node's disk
   - **The container's logs (and --previous), then describe for the exit code and events** (answer)
   - The Service
   Why: The app usually says why it exited. In the lab the log said "config error, DATABASE_URL is not set", exit code 1.

2. A Pod stays Pending with "0/2 nodes are available, 2 Insufficient cpu". What does it mean?
   - The image is missing
   - **No node has enough unreserved CPU for the Pod's request; lower the request, free capacity or add nodes** (answer)
   - The Pod crashed
   Why: Pending means not yet scheduled. The scheduler explains why in the Pod's events.

3. Which status means the image couldn't be pulled?
   - CrashLoopBackOff
   - **ErrImagePull, then ImagePullBackOff** (answer)
   - OOMKilled
   Why: The kubelet retries the pull with growing delays. Check the tag, the registry name and pull permissions.

## Resources

- [Debug running Pods](https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/) (Kubernetes)
- [Debug Pods](https://kubernetes.io/docs/tasks/debug/debug-application/debug-pods/) (Kubernetes)
- [Logging architecture](https://kubernetes.io/docs/concepts/cluster-administration/logging/) (Kubernetes)
- [Resource metrics pipeline](https://kubernetes.io/docs/tasks/debug/debug-cluster/resource-metrics-pipeline/) (Kubernetes)
