Skip to content

Kubernetes Observability & Troubleshooting: Events, Logs, kube-state-metrics, CrashLoopBackOff, OOMKilled ​

"In a cluster, logs should have a separate storage and lifecycle independent of nodes, pods, or containers." — Kubernetes documentation, Logging Architecture (concepts/cluster-administration/logging)

Summary: Kubernetes tells you what went wrong in four places that expire at different speeds (object status, Events kept about an hour, container logs kept until the next rotation or eviction, and metrics kept as long as Prometheus keeps them); troubleshooting is the habit of reading them in a fixed order, and observability is the work of making sure they still exist when you need them. Focus: The troubleshooting method (symptom, object, events, describe, logs, exec or debug, node); Events (types, reasons, the API server's event TTL, kubectl get events and kubectl events, event exporters); container logs (kubectl logs with --previous, --since, -l, --all-containers, the CRI log format, kubelet log rotation, sidecar and node-agent patterns); kubectl debug with ephemeral containers, Pod copies and debug node; netshoot; the metrics stack (metrics-server vs kube-state-metrics vs node-exporter vs cAdvisor; Prometheus Operator with ServiceMonitor, PodMonitor, PrometheusRule, Alertmanager; kube-prometheus-stack; Grafana; USE and RED); log and trace pipelines (OpenTelemetry Collector as DaemonSet vs Deployment, Fluent Bit, Vector, Loki, Tempo); every classic failure state (Pending and FailedScheduling, ImagePullBackOff and ErrImagePull, CrashLoopBackOff, OOMKilled with exit code 137, CreateContainerConfigError, readiness probe failing, Terminating stuck on finalizers, Evicted, NodeNotReady and node pressure, CoreDNS and ndots, Service without endpoints, NetworkPolicy drops, PVC Pending); API server and etcd health; kubectl plugins (krew, stern, k9s, kubectl-neat); runbooks and on-call; and a Go service and a Laravel app that are easy to observe. Learning goal: Take any broken Pod, Service or node and find the cause with a repeatable sequence of read-only commands; know which signal lives where and how long it survives; install and configure the Prometheus Operator objects, a log pipeline and an OpenTelemetry Collector; and ship a Go and a Laravel service whose metrics, JSON logs and correlation ids make the next incident short.

This is the operations chapter of the Kubernetes group. The concepts it relies on are owned elsewhere and only summarised here: what logs, metrics and traces are and how to design them is Observability: Logs, Metrics, Traces and the Stack; SLOs, burn-rate alerts and paging policy are Alerting That Actually Works; why an organisation runs Kubernetes at all is Containers & Kubernetes. The objects being debugged come from the earlier chapters: the control plane, the kubelet and kubectl from Kubernetes Architecture & Setup; Pods, probes and rollouts from Kubernetes Workloads; ConfigMaps, Secrets and PVCs from Kubernetes Config, Secrets & Storage; requests, limits, QoS, eviction and the scheduler from Resources, Scheduling & Autoscaling; RBAC and audit policy from Kubernetes Security. Cluster networking (CNI, kube-proxy, CoreDNS, NetworkPolicy semantics) is Kubernetes Networking, generic "refused vs timeout" network debugging is the Network Troubleshooting Playbook, and DNS resolution on a host is DNS Resolution for Developers. Below the container, strace, perf and eBPF are Linux Debugging, and process and filesystem basics are Linux for Developers. Structured logging in Go itself (log/slog, flags, env) is CLI, Flags, Env & Logging.

Page map ​

If you are looking forGo to
The whole chapter in three tablesEverything in one minute
Why Kubernetes needs its own debugging habitsWhy it exists
metrics-server (inspired by Heapster), the CRI log format, ephemeral containers GA, /healthz deprecationWhere it comes from
The fixed order of questions for any incidentThe troubleshooting method
kubectl describe, kubectl get events, kubectl events, event TTLEvents
kubectl logs flags, --previous, multi-container Podskubectl logs
Where log files live, CRI log format, containerLogMaxSizeNode logs and rotation
kubectl exec, kubectl debug, ephemeral containers, --copy-to, debug nodeGetting a shell
netshoot, kubectl port-forward, EndpointSlicesNetwork debugging tools
metrics-server vs kube-state-metrics vs node-exporter vs cAdvisorThe four metric sources
ServiceMonitor, PodMonitor, PrometheusRule, Alertmanager, kube-prometheus-stackPrometheus Operator
Grafana, USE and RED, the signals that matter for Pods and nodesDashboards and key signals
OpenTelemetry Collector agent vs gateway, Fluent Bit, Vector, Loki, TempoLog and trace pipelines
Pending / FailedSchedulingPending
ImagePullBackOff, ErrImagePull, CreateContainerConfigErrorCannot start
CrashLoopBackOff and exit codesCrashLoopBackOff
OOMKilled, exit code 137, CPU throttlingOOMKilled and saturation
Readiness probe failingNot Ready
Terminating stuck, finalizersTerminating
Evicted, node pressure, NodeNotReadyNode problems
CoreDNS, ndots, DNS debuggingDNS
Service without endpoints, selector mismatch, NetworkPolicy dropService and network
PVC PendingPVC Pending
livez, readyz, etcd health, audit previewControl plane health
krew, stern, k9s, kubectl-neatkubectl plugins
Runbooks, on-call basicsRunbooks and on-call
Events pipeline, label cardinality, error stringsMechanics
CodeGo, Laravel
Ten classic problems and their fixesSolving the classic problems
Which tool for which jobChoosing
From one Deployment to many clustersIn architecture
Commands to tryLab

Everything in one minute ​

Where each signal lives, and how long it survives

SignalWhere it is storedLifetime by defaultRead it with
Object status (phase, conditions, container state, restart count)etcd, via the API serverAs long as the object existskubectl get -o wide, kubectl describe, -o yaml
Events (Normal, Warning)etcd, as Event objects--event-ttl on kube-apiserver, default 1h0m0skubectl events, kubectl get events, bottom of kubectl describe
Container logsFiles on the node under /var/log/podsUntil rotated (containerLogMaxSize 10Mi, containerLogMaxFiles 5), the Pod is evicted, or the node dies; one terminated container keptkubectl logs, --previous
Termination messageContainer statusWith the Podkubectl describe, .status.containerStatuses[].lastState
Resource usage nowmetrics-server memoryOnly the latest scrapekubectl top pod/node
Metrics historyPrometheus TSDBIts retention (chart default 10d in kube-prometheus-stack)Grafana, PromQL
Shipped logsLoki, Elasticsearch, a vendorThe backend's retentionGrafana Explore, LogQL
TracesTempo, Jaeger, a vendorThe backend's retentionGrafana, TraceQL

Status you see → what it means → first command

kubectl get pods showsMeansFirst command
Pending (NODE <none>)Phase Pending and not scheduled yet (or volumes not bound)kubectl describe pod → FailedScheduling event
ContainerCreating for minutesScheduled; image pull, volume mount or sandbox is slow or failingkubectl events --for pod/NAME
ErrImagePull, then ImagePullBackOffPull failed; the kubelet retries with back-off up to 300 skubectl describe pod (image name, auth)
CreateContainerConfigErrorThe container spec references a ConfigMap, Secret or key that is missingkubectl describe pod → message names it
CrashLoopBackOffThe container keeps exiting; restarts back off 10 s, 20 s, 40 s … capped at 300 skubectl logs --previous, last exit code
OOMKilled (as last state), exit code 137The kernel's OOM killer killed the process: usually at the container's memory limit, sometimes in a node-wide OOMkubectl describe pod, container_memory_working_set_bytes, node memory
Running but 0/1 READYReadiness probe failing; removed from Service endpointskubectl describe pod → Unhealthy events
Terminating for minutesDeletion requested; finalizers or a webhook keep the objectkubectl get pod -o yaml → metadata.finalizers
Evicted, Error, many Pods on one nodeNode pressure or a lost nodekubectl describe node → conditions
Pods fine, requests failService has no endpoints, DNS, or NetworkPolicykubectl get endpointslices -l kubernetes.io/service-name=NAME

Which metric source answers which question

ComponentRuns asAnswersTypical series
cAdvisor (inside the kubelet)Part of every kubeletHow much CPU/memory/network does each container use?container_cpu_usage_seconds_total, container_memory_working_set_bytes, container_cpu_cfs_throttled_periods_total
metrics-serverDeploymentWhat is usage right now, for HPA, VPA and kubectl top?Metrics API metrics.k8s.io (no Prometheus series)
kube-state-metricsDeploymentWhat state are the objects in?kube_pod_status_phase, kube_pod_container_status_waiting_reason, kube_node_status_condition
node-exporterDaemonSetHow is the machine itself doing?node_cpu_seconds_total, node_filesystem_avail_bytes (port 9100)
Your appYour PodsIs the service doing its job?http_requests_total, http_request_duration_seconds
Troubleshooting method: start from what kubectl get pods shows, then follow one branchkubectl get pods -o wideSTATUS, READY, RESTARTS, NODEPendingFailedScheduling event:resources, taints,affinity, PVC unboundImagePullBackOffalso ErrImagePull,InvalidImageName: tag,registry auth, secretCreateContainer-ConfigError: missingConfigMap / Secretor key in itCrashLoopBackOfflogs --previous andexit code: 137 = OOMor SIGKILL, 1 = appRunning, 0/1 Readyreadiness probe fails:Unhealthy events,deps and timeoutsThe Pod looks healthy, or the cause is outside it:Running and Ready, but failingService: EndpointSlices empty?selector or targetPort mismatch,DNS (CoreDNS, ndots), NetworkPolicyTerminating for minutesfinalizers not removed, or awebhook blocking UPDATE:read metadata.finalizersEvicted, Unknown, many Pods at oncea node problem: describe node,MemoryPressure, DiskPressure,NodeNotReady; kubectl debug node/Every branch uses the same order: object status -> events (kubectl events --for) -> describe -> logs (current, --previous) ->exec / ephemeral debug container -> node. Metrics (kube-state-metrics, cAdvisor) tell you when it started and how many Pods share it.Events expire (kube-apiserver --event-ttl, default 1h): collect them first or export them.

Why it exists ​

On one server a broken service leaves its evidence in one place: a process list, /var/log, a core dump. On Kubernetes the same failure is spread across a scheduler decision (stored as an Event), a kubelet that tried and backed off (more Events and a container state), a container that wrote to stdout and was then replaced (its log is now the "previous" one, and only one previous is kept), a node that may already be gone, and a controller that keeps creating fresh Pods with new names. Evidence is also short-lived by design: Events expire after an hour by default, kubectl logs reads only the newest rotated file, and an evicted Pod takes its logs with it.

That gives the chapter its two halves. Troubleshooting is a fixed order of read-only questions that collects the short-lived evidence first. Observability is the platform work that copies the evidence somewhere durable before it expires: Prometheus for metrics, a node agent for logs, an exporter or the OpenTelemetry Collector for Events, and traces for the requests that cross services.

Without a method and a pipelineWith them
kubectl get pods, then guess, then kubectl delete pod (and the evidence)Status, events, describe, logs --previous, then act
"It crashed at 03:00", but the Events are gone by 09:00Events exported to the log backend and kept for weeks
Restarted container's logs lostNode agent shipped every line; kubectl logs --previous as backup
Dashboards of CPU per nodeRED per service (what users feel) and USE per node (why)
Alerts on every CPU spikeAlerts on symptoms (error ratio, latency), causes on dashboards
Logs that need a regexJSON lines with level, correlation_id, trace_id

An everyday picture. A hospital ward at shift change. The patient's chart at the bed is the object status: what is true now. The nurse's notes are the Events: short entries ("fever 39 °C, called doctor") that the ward throws away after a day. The heart monitor is the metrics stream, useful only if someone records it. The patient's own description is the log, and it is gone if the patient is moved to another ward and nobody wrote it down. A good doctor reads them in the same order every time, chart first and notes before they are discarded, and the hospital's job is to archive the notes and the monitor trace. We will use this picture again.

Three common misunderstandings, up front ​

  • "kubectl logs shows me what happened." It shows the current container's newest log file. After a crash you need --previous; after a rotation the older lines are only on the node; after an eviction or a node loss they are gone unless a node agent shipped them.
  • "metrics-server is our monitoring." Its own README says it is "meant only for autoscaling purposes" and should not be used "as a source of monitoring solution metrics". It keeps the latest value only. Monitoring is Prometheus scraping the kubelet, kube-state-metrics, node-exporter and your apps.
  • "Deleting the Pod fixes it." A Deployment replaces it with the same spec, so the same failure returns, and the old Pod's Events, previous logs and termination message are lost. Collect first, then delete if you must.

Where it comes from ​

WhenWhat changedWhy it matters here
2016The CRI logging design: the runtime writes each line with an RFC 3339Nano timestamp, the stream, a P/F tag and the contentEvery node agent parses this format; partial lines (P) are why multiline parsers exist
2012–2013Brendan Gregg publishes the USE method ("For every resource, check utilization, saturation, and errors")The checklist for nodes and containers
2018Tom Wilkie's RED method (Rate, Errors, Duration)The checklist for services; Grafana's dashboard guide uses both
Kubernetes 1.16API server /healthz deprecated in favour of /livez and /readyzLoad balancers and scripts should call the specific endpoints
Kubernetes 1.21Container log rotation by the kubelet marked stable (containerLogMaxSize, containerLogMaxFiles)The 10Mi × 5 defaults decide how much kubectl logs can show
Kubernetes 1.25Ephemeral containers stablekubectl debug works on distroless Pods without changing them
Kubernetes 1.27The kubelet moves deleted Pods to a terminal phase before deletion from the API serverFewer Pods stuck in a non-terminal phase after deletion
2021The original Opsgenie kubernetes-event-exporter stops being maintained; the Resmo fork continuesPick a maintained exporter or the OpenTelemetry k8sobjects receiver
kubectl v1.36 (client used for this chapter)kubectl debug --profile defaults to general; the options are general, baseline, restricted, netadmin, sysadminThe task page's older text still says legacy is the default; the client is authoritative
2026kube-prometheus-stack chart 94.2.1 ships Prometheus Operator v0.95.2; client_golang v1.24+ needs Go 1.25Versions pinned in this chapter's snippets

kube-state-metrics' README describes metrics-server as "a project that has been inspired by Heapster" and implemented to serve the core metrics pipeline, while kube-state-metrics exposes object state for monitoring; together with Prometheus (and the Prometheus Operator that configures it) that is why there are now two pipelines (diagram below).

The concept catalogue ​

Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, per-tool behaviour, and the fix.

The troubleshooting method Must-know ​

In plain words: Ask the same questions in the same order every time: what does the object say, what did the system do about it (Events), what did the process say (logs, including the previous run), what can I see from inside (exec or a debug container), and is the node itself healthy.

Common misunderstanding: "Start with the logs." For half the failure states there are no logs at all: a Pending Pod never started, an ImagePullBackOff container never ran, and CreateContainerConfigError happens before the process exists. The answer is in the Events and the container state.

Definition: The troubleshooting method used in this chapter is: (1) symptom: who sees what (an alert, a 502, a stuck rollout); (2) object: kubectl get the workload and its Pods with -o wide (status, restarts, node); (3) events: kubectl events --for pod/NAME or the bottom of kubectl describe; (4) describe: conditions, container state and last state with exit code, probes, mounts; (5) logs: current and --previous, all containers; (6) inside: kubectl exec, or kubectl debug with an ephemeral container when the image has no shell; (7) node: kubectl describe node, kubectl debug node/NAME, kubelet and runtime logs. Metrics answer the two questions the steps cannot: since when and how many Pods share the problem.

text
Sequence (orders-api returns 503 after a deploy)
1  alert: OrdersAPIHighErrorRate fires (5xx ratio 0.31 for 5m)
2  kubectl get deploy,rs,pods -n shop -l app.kubernetes.io/name=orders-api -o wide
     -> new ReplicaSet 0/3 ready, pods RESTARTS 4, STATUS CrashLoopBackOff
3  kubectl events -n shop --for pod/orders-api-7d9c
     -> Warning BackOff  kubelet  Back-off restarting failed container
4  kubectl describe pod orders-api-7d9c -n shop
     -> Last State: Terminated, Reason: Error, Exit Code: 1
5  kubectl logs orders-api-7d9c -n shop --previous
     -> {"level":"ERROR","msg":"exit","err":"DATABASE_URL: missing"}
6  fix: the new Secret key name; rollout undo while the fix ships

Real scenarios: a rollout stuck at 1 of 3 new Pods; a CronJob that "did not run" (the Job's Pod was Pending on a tainted node pool); a 502 from the Ingress where every Pod is Running (the Service selector lost a label in a Helm chart refactor); a Monday-morning page where the cause happened on Saturday (Events gone, so only exported Events and metrics can answer).

StepToolTypical findingTime-sensitive?
Objectkubectl get -o widePhase, READY, RESTARTS, NODE, ageNo
Eventskubectl events --forFailedScheduling, BackOff, Unhealthy, FailedMountYes: default 1 h
Describekubectl describeExit code, OOMKilled, probe config, image, mountsLast state only
Logskubectl logs, --previousStack trace, config errorYes: rotation, eviction
Insidekubectl exec, kubectl debugDNS, connectivity, files, processesLive only
Nodedescribe node, debug nodePressure, NotReady, kubelet errorsLive only

Fix / how to use it: the runbook script in this chapter's snippets runs steps 2–5 and the Service and node checks read-only and prints every command it runs:

bash
#!/usr/bin/env bash
# k8s-triage.sh - read-only first-response collector for the on-call runbook.
# It walks the troubleshooting method: object -> events -> describe -> logs
# (current and previous) -> endpoints / node, and never changes the cluster.
#
#   k8s-triage.sh pod     <namespace> <pod>
#   k8s-triage.sh deploy  <namespace> <deployment>
#   k8s-triage.sh svc     <namespace> <service>
#   k8s-triage.sh node    <node>
#   k8s-triage.sh dns
#   k8s-triage.sh cluster
#
# KUBECTL overrides the binary (KUBECTL="echo kubectl" prints the plan).
# Save the output with: k8s-triage.sh pod shop orders-api-7d9c 2>&1 | tee triage.txt
set -euo pipefail

read -r -a K <<< "${KUBECTL:-kubectl}"
K+=(--request-timeout=20s)

section() { printf '\n===== %s =====\n' "$*"; }
# run prints the command, runs it, and keeps going if it fails: a missing
# previous container or an absent metrics-server must not stop the triage.
run() { printf '$ kubectl %s\n' "$*"; "${K[@]}" "$@" || printf '(exit %d)\n' "$?"; }

usage() {
  sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//'
  exit 2
}

pod() {
  local ns=$1 name=$2
  section "pod $ns/$name: status and placement"
  run get pod "$name" -n "$ns" -o wide
  section "container states (reason / exit code of the last termination)"
  run get pod "$name" -n "$ns" -o jsonpath='{range .status.containerStatuses[*]}{.name}{"\t"}ready={.ready}{"\t"}restarts={.restartCount}{"\t"}waiting={.state.waiting.reason}{"\t"}last={.lastState.terminated.reason}/{.lastState.terminated.exitCode}{"\n"}{end}'
  section "events for this pod, oldest first (kept about 1h by default)"
  run events -n "$ns" --for "pod/$name"
  section "describe (conditions, probes, mounts, events)"
  run describe pod "$name" -n "$ns"
  section "logs: current containers, last 200 lines each"
  run logs "$name" -n "$ns" --all-containers --tail=200 --timestamps
  section "logs: previous instance (the crash itself, if it restarted)"
  run logs "$name" -n "$ns" --all-containers --previous --tail=200 --timestamps
  section "resource usage (needs metrics-server)"
  run top pod "$name" -n "$ns" --containers
}

deploy() {
  local ns=$1 name=$2
  section "deployment $ns/$name"
  run rollout status "deployment/$name" -n "$ns" --timeout=10s
  run get deployment "$name" -n "$ns" -o wide
  run get replicasets -n "$ns" -o wide
  section "pods of the deployment"
  local selector
  selector=$("${K[@]}" get deployment "$name" -n "$ns" -o go-template='{{range $k, $v := .spec.selector.matchLabels}}{{$k}}={{$v}},{{end}}' 2>/dev/null || true)
  selector=${selector%,}
  if [[ -n $selector ]]; then
    run get pods -n "$ns" -l "$selector" -o wide
    run logs -n "$ns" -l "$selector" --all-containers --prefix --tail=50 --max-log-requests=10
  fi
  section "warning events in $ns"
  run events -n "$ns" --types=Warning
}

svc() {
  local ns=$1 name=$2
  section "service $ns/$name"
  run get service "$name" -n "$ns" -o wide
  run get service "$name" -n "$ns" -o jsonpath='selector={.spec.selector}{"\n"}ports={.spec.ports}{"\n"}'
  section "endpoint slices (empty ENDPOINTS = selector matches no ready pod)"
  run get endpointslices -n "$ns" -l "kubernetes.io/service-name=$name" -o wide
  section "pods matching the selector"
  local selector
  selector=$("${K[@]}" get service "$name" -n "$ns" -o go-template='{{range $k, $v := .spec.selector}}{{$k}}={{$v}},{{end}}' 2>/dev/null || true)
  selector=${selector%,}
  [[ -n $selector ]] && run get pods -n "$ns" -l "$selector" -o wide --show-labels
  section "network policies that could drop the traffic"
  run get networkpolicies -n "$ns"
}

node() {
  local name=$1
  section "node $name"
  run get node "$name" -o wide
  run get node "$name" -o jsonpath='{range .status.conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}'
  run top node "$name"
  section "pods on the node"
  run get pods -A --field-selector "spec.nodeName=$name" -o wide
  section "node events"
  run events -A --for "node/$name"
  echo
  echo "# Next step if the node is NotReady and reachable (creates a privileged debug pod; chroot needs sysadmin):"
  echo "#   kubectl debug node/$name -it --profile=sysadmin --image=busybox:1.37 -- chroot /host journalctl -u kubelet --since -30m"
}

dns() {
  section "CoreDNS pods, service and endpoints"
  run get pods -n kube-system -l k8s-app=kube-dns -o wide
  run get service kube-dns -n kube-system
  run get endpointslices -n kube-system -l kubernetes.io/service-name=kube-dns
  section "CoreDNS logs (errors plugin output)"
  run logs -n kube-system -l k8s-app=kube-dns --tail=50 --prefix
  echo
  echo "# Next step (creates a throwaway pod): resolve from inside the cluster"
  echo "#   kubectl run dns-test -n <ns> --rm -it --restart=Never --image=nicolaka/netshoot:v0.17 -- \\"
  echo "#     sh -c 'cat /etc/resolv.conf; dig +search orders-api; dig orders-api.shop.svc.cluster.local'"
}

cluster() {
  section "API server health"
  run get --raw='/livez'
  run get --raw='/readyz?verbose'
  section "nodes"
  run get nodes -o wide
  section "warning events, all namespaces"
  run events -A --types=Warning
  section "pods that are not Running or Succeeded"
  run get pods -A --field-selector=status.phase!=Running,status.phase!=Succeeded -o wide
}

cmd=${1:-}
case $cmd in
  pod|deploy|svc) [[ $# -eq 3 ]] || usage; "$cmd" "$2" "$3" ;;
  node) [[ $# -eq 2 ]] || usage; node "$2" ;;
  dns|cluster) [[ $# -eq 1 ]] || usage; "$cmd" ;;
  *) usage ;;
esac

Events: kubectl describe, kubectl get events, kubectl events, event TTL Must-know ​

In plain words: Events are short notes that controllers and the kubelet attach to objects: "scheduled to node 3", "pulling image", "back-off restarting", "readiness probe failed". They are the nurse's notes from the everyday picture, and they are thrown away after about an hour.

Common misunderstanding: "Events are a log of everything that ever happened to my Pod." They are deduplicated (a repeated event increases a count and series instead of creating a new object), namespaced, best-effort, and deleted when the API server's event TTL expires; the default is 1h0m0s (kube-apiserver --event-ttl, "Amount of time to retain events").

Definition: An Event (events.k8s.io/v1, also readable through the core v1 API) has a type ("Normal, Warning"), a machine-readable reason (FailedScheduling, BackOff, Unhealthy, FailedMount, Pulling, Killing, NodeNotReady, Evicted), a human-readable note (shown as message), the object it is about (regarding), the emitting reportingController (for example kubernetes.io/kubelet) and, for repeats, series. Warning events are the ones that matter during an incident. Three ways to read them:

CommandScopeSortedNotes
kubectl describe pod NAMEOne objectAs listed, at the endThe quickest; shows Events together with state and probes
kubectl get events -n NS --sort-by=.lastTimestampNamespace (or -A)By the JSONPath you give--sort-by takes a JSONPath; without it the order is not chronological
kubectl events -n NS --for pod/NAME --types=WarningOne object or namespaceOldest first--watch streams new ones; --types=Warning,Normal filters
kubectl get events --field-selector type=Warning -AClusterUnsortedGood for a cluster-wide sweep
text
Sequence: why the 03:00 crash has no Events at 09:00
03:00  kubelet emits Warning BackOff (count 1), then increments the series count
03:10  last update of the Event
04:10  API server's TTL (default 1h) deletes it from etcd
09:00  on-call runs kubectl events: nothing; only an event exporter or the
       OpenTelemetry k8sobjects receiver kept a copy in the log backend

Real scenarios: FailedScheduling explains a stuck Pod in one line ("0/6 nodes are available: 3 Insufficient cpu, 3 node(s) had untolerated taint(s)"); FailedMount explains ContainerCreating for ten minutes; Unhealthy with "Readiness probe failed: HTTP probe failed with statuscode: 503" explains a Pod that runs but takes no traffic; a burst of Killing and Preempting events shows a higher-priority workload pushed yours out.

Event exporterWhat it doesNotes
kubernetes-event-exporter (Resmo fork)Watches Events, routes them to Elasticsearch, webhooks, Slack, Loki and othersThe Opsgenie original is unmaintained since November 2021
OpenTelemetry Collector k8sobjects receiverPulls or watches objects, most commonly Events, into the logs pipelineRun one instance (gateway Deployment, 1 replica) or you get duplicates
kube-state-metricsDoes not export EventsIt exports object state, a different signal

Fix / how to use it: read Events before you delete anything; export them in every cluster so incidents older than an hour can be investigated (the OpenTelemetry gateway values in this chapter enable the kubernetesEvents preset); and alert on states (kube-state-metrics) rather than on individual Events, which are best-effort.

kubectl logs: --previous, --since, -l selector, --all-containers Must-know ​

In plain words: kubectl logs asks the kubelet on the Pod's node to read the container's log file and stream it back. It can read the current container, or the one that ran before the last restart.

Common misunderstanding: "If the container restarted, the crash is in kubectl logs." The plain command shows the new container, which usually starts cleanly and then dies again. The crash is in kubectl logs --previous ("print the logs for the previous instance of the container in a pod if it exists"), and the kubelet keeps only one terminated container per container.

Definition: the flags that matter, verified against the v1.36 client help:

FlagMeaningDefault
-c NAMEContainer in a multi-container PodThe Pod's default container
--all-containersEvery container in the Pod(s)false
-p, --previousThe previous instance of the containerfalse
-f, --followStreamfalse
--since=1h, --since-time=RFC3339Only newer linesAll
--tail=NLast N lines-1 (all) without a selector, 10 with one
-l app=orders (the -l selector form)All Pods matching labelsUp to --max-log-requests (default 5) concurrent streams
--prefixPrefix each line with pod and container namefalse (true with --all-pods)
--timestampsAdd the runtime timestampfalse
--limit-bytesStop after N bytesNo limit
deploy/NAME, job/NAMEPick one Pod of the controller—
text
Sequence: a crash loop, seen with and without --previous
1  container #0 starts, logs "listening", panics at 12:00:07, exit 2
2  kubelet restarts it after 10 s back-off -> container #1
3  kubectl logs pod/x               -> "listening" (container #1, healthy so far)
4  kubectl logs pod/x --previous    -> "panic: nil map" + stack (container #0)
5  container #1 dies too; #0 is discarded, #1 becomes "previous"

Real scenarios: an init container failing (kubectl logs pod/x -c migrate); a sidecar (Envoy, php-fpm exporter, Cloud SQL proxy) failing while the app looks fine (--all-containers --prefix); tailing a whole Deployment during a rollout (kubectl logs -l app.kubernetes.io/name=orders-api --prefix -f --max-log-requests=10, or stern); a Job that finished (logs stay while the Pod object exists; ttlSecondsAfterFinished deletes them).

ToolMulti-PodFollows new PodsColour/filters
kubectl logs -lYes, up to --max-log-requestsNo--prefix only
sternYes (regex or deployment/name)Yes: "if a new pod is added it automatically gets tailed"Colour per Pod, --since default 48h, -o json
k9sInteractiveYesLogs view per Pod/container
Loki / Grafana ExploreEvery Pod, any time range—LogQL label and JSON filters

Fix / how to use it: use --previous for any Pod with restarts; --all-containers --prefix for any multi-container Pod; --since=15m during an incident to keep output small; and write JSON lines so kubectl logs ... | jq 'select(.level=="ERROR")' works without a log backend.

Node logs: CRI log format and log rotation containerLogMaxSize Important ​

In plain words: Your process writes to stdout; the container runtime (containerd, CRI-O) writes each line to a file on the node, prefixed with a timestamp and the stream name; the kubelet rotates the file when it grows; kubectl logs and every node agent read those files.

Common misunderstanding: "kubectl logs returns everything the container wrote." The docs say: "Only the contents of the latest log file are available through kubectl logs. For example, if a Pod writes 40 MiB of logs and the kubelet rotates logs after 10 MiB, running kubectl logs returns at most 10MiB of data."

Definition: The CRI log format decorates "each log entry with a RFC 3339Nano timestamp prefix, the stream type (i.e., "stdout" or "stderr"), the tags of the log entry, the log content". The only tag is partial (P, the runtime split a long line) or full (F). The kubelet directs the runtime to write under /var/log/pods (changeable with podLogsDir, at your own risk), and rotation is configured on the kubelet with containerLogMaxSize (default 10Mi) and containerLogMaxFiles (default 5), plus containerLogMaxWorkers and containerLogMonitorInterval (default 10 s). On systemd nodes the kubelet and the runtime themselves log to journald (journalctl -u kubelet).

text
What containerd writes for one JSON log line and one long line split in two
2026-11-29T10:41:07.120441812Z stdout F {"level":"INFO","msg":"request","status":200}
2026-11-29T10:41:07.120902117Z stderr P first 16 KiB of a very long stack trace ...
2026-11-29T10:41:07.120903001Z stderr F ... the rest of it

Real scenarios: a chatty debug log rotating every few seconds, so kubectl logs shows only the last ten seconds; a node agent that does not understand P lines splitting a stack trace into fragments; a team that writes logs to a file inside the container (invisible to kubectl logs, lost on restart, and counted against ephemeral storage); /var/log on a separate disk that the kubelet does not track, filling up silently.

Runtime / settingBehaviour
containerd, CRI-OWrite the CRI format; the kubelet owns rotation
Docker Engine (dockershim, removed in 1.24)Wrote JSON files with its own max-size driver options; old guides still mention them
Kubelet containerLogMaxSize / containerLogMaxFiles10Mi / 5 by default; per container
Fluent Bit tail inputmultiline.parser docker, cri reassembles P + F lines
OpenTelemetry filelog receiver (Helm logsCollection preset)Reads /var/log/pods/*/*/*.log

Fix / how to use it: keep the kubelet defaults unless volume demands more (the kubelet-config.yaml snippet shows the knobs), never log to files inside the container, write one JSON object per line to stdout or stderr, and ship with a node agent so rotation does not matter.

yaml
# KubeletConfiguration fragment (node-level; set by kubeadm, the node image or
# the managed provider). Shown so the defaults that shape logs and eviction
# are visible.
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
# Container log rotation: the defaults are 10Mi and 5 files per container.
# `kubectl logs` reads only the newest file.
containerLogMaxSize: 50Mi
containerLogMaxFiles: 5
# Hard eviction thresholds; these values are the Linux defaults. Setting any
# of them replaces the whole default map: thresholds you leave out are set to
# zero (disabled) unless mergeDefaultEvictionSettings is true, so list all five.
evictionHard:
  memory.available: "100Mi"
  nodefs.available: "10%"
  imagefs.available: "15%"
  nodefs.inodesFree: "5%"
  imagefs.inodesFree: "5%"

Getting a shell: kubectl exec, kubectl debug, ephemeral container, debug node Must-know ​

In plain words: kubectl exec runs a command inside an existing container. kubectl debug adds a temporary container with your tools to a running Pod (an ephemeral container), or makes a modified copy of the Pod, or starts a Pod on a node with access to the host.

Common misunderstanding: "To debug a distroless image I have to rebuild it with a shell." The Kubernetes docs list exactly this case: an ephemeral container is "useful for interactive troubleshooting when kubectl exec is insufficient because a container has crashed or a container image doesn't include debugging utilities, such as with distroless images".

Definition: an ephemeral container (stable since Kubernetes 1.25) runs temporarily in an existing Pod; it shares the Pod's network namespace, and with --target=CONTAINER it joins that container's process namespace so ps and /proc/1/root show the app. Ephemeral containers "lack guarantees for resources or execution, and they will never be automatically restarted"; ports, livenessProbe, readinessProbe and resources are disallowed, and once added they cannot be changed or removed. They are added through the pods/ephemeralcontainers subresource, so RBAC needs update/patch on it, which the built-in edit and admin roles deliberately do not include; without it you get pods "example" is forbidden: User "alice" cannot patch resource "pods/ephemeralcontainers".

CommandWhat it createsUse it whenWatch out
kubectl exec -it POD -c C -- shA process in the existing containerThe image has a shell and toolsDistroless: executable file not found in $PATH
kubectl debug -it POD --image=busybox:1.37 --target=appAn ephemeral container in the same PodDistroless images, live inspection without restartCannot be removed; needs RBAC; Pod Security applies
kubectl debug POD -it --copy-to=POD-debug --container=app -- shA copy of the Pod with the command changedThe app crashes on start and you need to look before it exitsThe copy has new labels unless --keep-labels; it is not behind the Service
kubectl debug POD --copy-to=POD-debug --set-image=*=ubuntuA copy with different imagesYou need a debug build of the image--share-processes defaults to true for copies
kubectl debug node/NODE -it --image=busybox:1.37A Pod on the node in the host IPC, network and PID namespaces, node root at /host (not privileged: chroot /host needs --profile=sysadmin)Kubelet, runtime, disk, iptables problemsNot privileged unless --profile=sysadmin; delete the Pod afterwards

Debugging profiles (--profile): general (the default in the v1.36 client), baseline and restricted (compatible with those Pod Security Standards), netadmin (network administrator capabilities, for tcpdump and iptables), and sysadmin (privileged). A --custom file can add a partial container spec on top.

text
Sequence: inspecting a distroless Go Pod that answers 500
1  kubectl exec -it orders-api-7d9c -- sh
     -> exec: "sh": executable file not found in $PATH
2  kubectl debug -it orders-api-7d9c --image=nicolaka/netshoot:v0.17 --target=orders-api --profile=general
     -> Defaulting debug container name to debugger-x2k4f.
3  (debugger) curl -s localhost:9090/metrics | grep http_requests_total
4  (debugger) dig +search postgres          # DNS from the Pod's own resolv.conf
5  (debugger) ls /proc/1/root/etc/orders    # the app's files via the shared PID namespace
6  kubectl describe pod orders-api-7d9c     # "Ephemeral Containers:" section lists it

Real scenarios: checking whether a Pod can reach its database (nc -vz postgres 5432 from an ephemeral netshoot container); reading the config file a distroless binary actually loaded; running the crashing command by hand in a --copy-to copy with -- sh; a node with full disk (kubectl debug node/n1 -it --profile=sysadmin --image=busybox:1.37 -- chroot /host df -h; without a privileged profile "chroot /host will fail"); a CNI problem that needs tcpdump on the node (--profile=sysadmin).

Fix / how to use it: give the on-call group a role that includes pods/ephemeralcontainers, pods/exec, pods/portforward, logs, events and the Metrics API, and nothing that writes workloads:

yaml
# Who may debug: reading logs and events is ordinary, adding an ephemeral
# container is an UPDATE on pods/ephemeralcontainers and is NOT part of the
# built-in edit/admin roles. Bind this role to the on-call group only.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: oncall-debugger
rules:
  - apiGroups: [""]
    resources: [pods, pods/log, events, services, endpoints, nodes]
    verbs: [get, list, watch]
  - apiGroups: [discovery.k8s.io]
    resources: [endpointslices]
    verbs: [get, list, watch]
  - apiGroups: [events.k8s.io]
    resources: [events]
    verbs: [get, list, watch]
  - apiGroups: [""]
    resources: [pods/ephemeralcontainers]
    verbs: [patch, update]
  - apiGroups: [""]
    resources: [pods/portforward, pods/exec]
    verbs: [create]
  - apiGroups: [metrics.k8s.io]
    resources: [pods, nodes]
    verbs: [get, list]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: oncall-debugger
subjects:
  - kind: Group
    name: sre-oncall
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: oncall-debugger
  apiGroup: rbac.authorization.k8s.io
Five ways in: what each kubectl debugging command shares with the Pod or the nodePod orders-api-7d9c: containers share one network namespaceapp containerdistroless: no shellephemeral containerkubectl debug --target=appkubectl exec: a processinside the app container;on distroless it fails withexecutable file not foundsame network: curllocalhost, dig, tcpdump;--target also shows theapp container's processeskubectl debug --copy-toa new Pod from the spec;change image or commandkubectl port-forwardtunnel via the API serverto a Pod or Service portkubectl debug node/n1a Pod on the node withhost network, PID, IPC;node root at /host;--profile=sysadminfor privileged tools(tcpdump, crictl,journalctl)Defaults (kubectl v1.36 client): --profile=general. Ephemeral containers are GA since Kubernetes 1.25, cannot be removed or restarted,have no ports or probes, and need RBAC update on pods/ephemeralcontainers, which the built-in edit and admin roles do not grant.

Network debugging tools: netshoot, kubectl port-forward, EndpointSlice Important ​

In plain words: Most "the service is down" incidents are really "this Pod cannot reach that Pod". You need a container with curl, dig, nc, tcpdump in the right network namespace, a way to reach a Pod from your laptop, and a way to see which Pods a Service actually points at.

Common misunderstanding: "kubectl port-forward tests the Service." It does not go through the Service's virtual IP or kube-proxy. The client help says that with several matching Pods "a pod will be selected automatically" and "the forwarding session ends when the selected pod terminates". It proves that one Pod answers, not that the Service routes.

Definition: netshoot is "a Docker + Kubernetes network trouble-shooting swiss-army container" whose README lists three Kubernetes uses: an ephemeral container (kubectl debug POD -it --image=nicolaka/netshoot), a throwaway Pod (kubectl run tmp-shell --rm -i --tty --image nicolaka/netshoot), and a throwaway Pod on the host network (--overrides='{"spec": {"hostNetwork": true}}'). kubectl port-forward tunnels a local port to a Pod through the API server and the kubelet. An EndpointSlice is the object in which the EndpointSlice controller stores the result of evaluating a Service's selector; kubectl get endpointslices -l kubernetes.io/service-name=NAME shows the Pod IPs, ports and readiness behind a Service.

text
Sequence: from the outside in
1  laptop:   kubectl port-forward -n shop svc/orders-api 8080:80   # one Pod answers?
2  cluster:  kubectl run tmp --rm -it --restart=Never --image=nicolaka/netshoot:v0.17 -n shop -- \
               curl -sv http://orders-api/orders/42                 # DNS + Service VIP + kube-proxy
3  objects:  kubectl get endpointslices -n shop -l kubernetes.io/service-name=orders-api
4  pod:      curl from step 2 to the Pod IP and targetPort directly  # bypasses the Service
5  policy:   kubectl get networkpolicy -n shop                      # timeouts, not refusals

Real scenarios: a Service that works from inside the namespace but not from ingress-nginx (a NetworkPolicy); a gRPC client that keeps hitting one Pod (long-lived HTTP/2 connections through a ClusterIP, diagnosed by counting requests per Pod in metrics); an Ingress returning 503 because the EndpointSlice has only not-ready endpoints.

Symptom from netshootLikely layerNext look
NXDOMAIN / can't resolveDNS (CoreDNS, search path, typo)DNS
Connection refused immediatelyNothing listening on that port in the Pod, or wrong targetPortkubectl describe svc, container ports
TimeoutNetworkPolicy drop, CNI, firewall, wrong IPService and network
Works by Pod IP, fails by Service nameService selector, ports, kube-proxyEndpointSlices
Works from netshoot, fails from the appApp config (URL, TLS, proxy env)App logs, kubectl exec env

Fix / how to use it: pin the netshoot image by tag or digest (its README recommends a digest for production debug sessions), test in the order of the sequence above, and read the Network Troubleshooting Playbook for the TCP-level meaning of refused versus timeout.

The four metric sources: metrics-server, kube-state-metrics, node-exporter, cAdvisor Must-know ​

In plain words: Four different components produce "Kubernetes metrics", and they answer different questions: cAdvisor measures containers, node-exporter measures machines, kube-state-metrics describes objects, and metrics-server keeps the latest CPU and memory numbers for autoscalers.

Common misunderstanding: "kube-state-metrics shows CPU usage." It shows state: "It is not focused on the health of the individual Kubernetes components, but rather on the health of the various objects inside, such as deployments, nodes and pods." It exports the requests and limits you configured (kube_pod_container_resource_requests) but not usage; usage comes from cAdvisor.

Definition:

ComponentWhat it measuresHow it gets the dataExposed asDo not use it for
cAdvisorPer-container CPU, memory, filesystem, network, OOM eventsBuilt into the kubelet; reads cgroupsKubelet /metrics/cadvisor (Prometheus format)Object state
metrics-serverLatest CPU and memory per Pod and nodeScrapes kubelets' resource endpoint, "collecting metrics every 15 seconds"Metrics API metrics.k8s.io (aggregated API)Monitoring or history ("meant only for autoscaling purposes")
kube-state-metricsState of API objects: phases, conditions, reasons, replicas, requests, limitsWatches the API server/metrics on port 8080Usage numbers; deleted objects disappear from /metrics
node-exporterHost CPU, memory, disks, filesystems, networkReads /proc, /sys on the host/metrics on port 9100 (DaemonSet)Per-container numbers

The CPU number in kubectl top is "derived by taking a rate over a cumulative CPU counter provided by the kernel", and memory is "the working set ... at the instant the metric was collected", which "typically also includes some cached (file-backed) memory". Two different mechanisms act on memory: the container's limit is a cgroup limit enforced by the Linux kernel's out-of-memory subsystem ("If the container tries to allocate more memory than this limit, the Linux kernel out-of-memory subsystem activates"), while node-pressure eviction is the kubelet comparing node-level memory.available (derived from the cgroupfs, excluding inactive file pages) with its eviction thresholds. The working set is the closest per-container approximation of what counts in both, which is why container_memory_working_set_bytes, not RSS, is the usual series to alert on.

text
Sequence: who answers "why is the HPA not scaling?"
1  kubectl get hpa orders-api           -> TARGETS <unknown>/70%
2  kubectl top pod -n shop              -> error: Metrics API not available
3  kubectl get apiservice v1beta1.metrics.k8s.io   -> AVAILABLE False (metrics-server down)
4  fix metrics-server; Prometheus dashboards were unaffected (they scrape cAdvisor directly)

Real scenarios: an HPA stuck at <unknown> because metrics-server cannot reach the kubelets; a dashboard that shows 0 running Pods because kube-state-metrics was OOMKilled in a large cluster; node disk alerts from node-exporter while every container looks fine (images and logs filling /var); container memory charts that disagree with ps inside the container (working set includes page cache, RSS does not).

QuestionSeriesSource
Is any Pod not Running?kube_pod_status_phase{phase=~"Pending|Failed|Unknown"}kube-state-metrics
Which containers are waiting, and why?kube_pod_container_status_waiting_reasonkube-state-metrics
Was the last exit an OOM?kube_pod_container_status_last_terminated_reason{reason="OOMKilled"}kube-state-metrics
Restartskube_pod_container_status_restarts_totalkube-state-metrics
Memory against the limitcontainer_memory_working_set_bytes / kube_pod_container_resource_limits{resource="memory"}cAdvisor + kube-state-metrics
CPU throttlingcontainer_cpu_cfs_throttled_periods_total / container_cpu_cfs_periods_totalcAdvisor
OOM kills seencontainer_oom_events_totalcAdvisor
Node conditionskube_node_status_condition{condition="Ready",status="true"}kube-state-metrics
Node disknode_filesystem_avail_bytesnode-exporter
PVC stuckkube_persistentvolumeclaim_status_phase{phase="Pending"}kube-state-metrics

Fix / how to use it: install metrics-server for autoscaling and kubectl top, and the kube-prometheus-stack (which brings kube-state-metrics, node-exporter and the kubelet/cAdvisor scrape config) for monitoring. The Resources, Scheduling & Autoscaling chapter owns how HPA uses the Metrics API.

Two metric pipelines: the resource pipeline for autoscaling, the Prometheus pipeline for monitoringOn every nodekubelet + cAdvisorcontainer_cpu_*, container_memory_*/metrics/cadvisor, /metrics/resourcenode-exporter (DaemonSet)node_* host metrics, :9100your app: /metricspromhttp, php-fpm exporterOnce per clusterkube-state-metricskube_pod_status_phase, ...API server (object state)metrics-serverscrapes kubelets ~15 skeeps only the latestMetrics APImetrics.k8s.ioCPU + memory onlyHPA / VPAkubectl topPrometheusscrapes every target,stores the time series,evaluates rulesscrape (pull)Prometheus Operatorturns ServiceMonitor,PodMonitor, PrometheusRuleinto Prometheus configconfigAlertmanagergroup, inhibit, routeSlack / pagerGrafanadashboards, Exploremetrics-server is not a monitoring source; Prometheus scrapes the kubelet, exporters and apps directly.kube-prometheus-stack installs the operator, Prometheus, Alertmanager, Grafana, kube-state-metrics and node-exporter.

Prometheus Operator: ServiceMonitor, PodMonitor, PrometheusRule, Alertmanager, kube-prometheus-stack Must-know ​

In plain words: Instead of editing one big prometheus.yml, each team creates small Kubernetes objects next to its app ("scrape this Service on port metrics", "alert when the error ratio is above 5 %") and an operator turns them into Prometheus and Alertmanager configuration.

Common misunderstanding: "I applied a ServiceMonitor, so Prometheus scrapes my app." Only if the Prometheus object selects it. The selector fields follow label-selector semantics where "A null selector (field not specified) matches no objects", and kube-prometheus-stack by default renders serviceMonitorSelector: matchLabels: release: <release name>. A ServiceMonitor without that label is silently ignored; the same holds for PodMonitors and PrometheusRules (ruleSelector "by default ... is nil meaning that the operator picks up no rule" in plain operator installs).

Definition: the Prometheus Operator manages these custom resources: Prometheus, Alertmanager, ThanosRuler, PrometheusAgent (instance-based: they deploy components) and ServiceMonitor, PodMonitor, Probe, ScrapeConfig, AlertmanagerConfig, PrometheusRule (config-based). A ServiceMonitor selects Services by label and scrapes the endpoints behind them by port name; a PodMonitor "can bypass the service and find targets based on Pod labels"; a PrometheusRule holds alerting and recording rules that are "dynamically loaded without requiring a restart"; an AlertmanagerConfig is a namespaced slice of routing whose routes, with the default OnNamespace matcher strategy, "only process alerts that have a namespace label equal to the namespace of the object" (inhibition rules included, so cluster-wide inhibition such as NodeNotReady muting Pod alerts belongs in the global Alertmanager configuration). kube-prometheus-stack is the Helm chart that installs the operator, Prometheus, Alertmanager, Grafana with curated dashboards, kube-state-metrics, node-exporter and default rules (chart 94.2.1 ships operator v0.95.2; install with helm install RELEASE oci://ghcr.io/prometheus-community/charts/kube-prometheus-stack). With Helm v3 its CRDs "are not updated by default and should be manually updated".

text
Sequence: from YAML to a scraped target
1  kubectl apply -f orders-api.yaml servicemonitor.yaml       (label release: kube-prometheus-stack)
2  operator sees the ServiceMonitor matching prometheus.spec.serviceMonitorSelector
3  operator regenerates the Prometheus config Secret; config-reloader reloads Prometheus
4  Prometheus discovers EndpointSlices of Services labelled app.kubernetes.io/name=orders-api
5  scrapes PodIP:9090/metrics every 30s -> target "UP" in Status > Targets
6  PrometheusRule evaluated every 30s -> alert pending -> firing after "for: 5m"
7  Alertmanager groups and routes via the AlertmanagerConfig -> Slack or pager

Real scenarios: a team's ServiceMonitor created in its own namespace but Prometheus only watching monitoring (serviceMonitorNamespaceSelector); a target DOWN with a scrape timeout after a default-deny NetworkPolicy; alerts that never fire because the PrometheusRule lacks the release label; duplicate pages from two Prometheus replicas that Alertmanager deduplicates only if both point at the same Alertmanager cluster.

ObjectSelectsByUsed for
ServiceMonitorServices (then their endpoints)selector + namespaceSelector; endpoints[].port is the Service port nameApps behind a Service
PodMonitorPodsselector; podMetricsEndpoints[].port is the container port nameSidecars, DaemonSets, Pods without Services
ProbeStatic targets or Ingresses through a prober (blackbox exporter)prober + targetsSynthetic HTTP checks
ScrapeConfigAnything, including targets outside the clusterRaw scrape configEscape hatch
PrometheusRule—ruleSelector on PrometheusRecording and alerting rules
AlertmanagerConfigAlerts with the object's namespace labelalertmanagerConfigSelector on AlertmanagerPer-team routes and receivers

Fix / how to use it: the Go service gets a Service with a named metrics port and a ServiceMonitor carrying the chart's release label; the Laravel Pods get a PodMonitor; rules and routing live in the app's namespace:

yaml
# Prometheus Operator ServiceMonitor for the orders API.
# kube-prometheus-stack's Prometheus selects ServiceMonitors labelled
# release: <helm release name> unless
# prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues is false.
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: orders-api
  namespace: shop
  labels:
    release: kube-prometheus-stack
    team: orders
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: orders-api   # selects the Service, not the Pods
  namespaceSelector:
    matchNames: [shop]
  endpoints:
    - port: metrics          # the Service port NAME, not the number
      path: /metrics
      interval: 30s
      scrapeTimeout: 10s
      metricRelabelings:
        # Drop the Go runtime histograms nobody looks at; keeps series down.
        - sourceLabels: [__name__]
          regex: go_gc_.*_seconds_bucket
          action: drop
  # Copy a Pod label onto every scraped series.
  podTargetLabels: [app.kubernetes.io/version]
yaml
# PodMonitor: scrape Pods directly (no Service needed). Used for the Laravel
# Pods' php-fpm exporter sidecar and the app's own /metrics route.
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: shop-web
  namespace: shop
  labels:
    release: kube-prometheus-stack
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: shop-web
  podMetricsEndpoints:
    - port: fpm-metrics      # hipages/php-fpm_exporter on :9253
      interval: 30s
    - port: http             # Laravel route /metrics served through nginx
      path: /metrics
      interval: 30s
yaml
# PrometheusRule: recording rules for the orders API's RED signals, alerts on
# them (symptoms users feel), and Kubernetes-state alerts that point at the
# failure states this chapter diagnoses. kube-prometheus-stack already ships
# similar Kubernetes alerts (defaultRules); these are the minimal set written
# out so every expression can be read.
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: shop-rules
  namespace: shop
  labels:
    release: kube-prometheus-stack   # matched by the chart's ruleSelector
spec:
  groups:
    - name: orders-api.red
      interval: 30s
      rules:
        - record: route:http_requests:rate5m
          expr: sum by (namespace, route, code) (rate(http_requests_total{namespace="shop"}[5m]))
        - record: route:http_request_errors:ratio_rate5m
          expr: |
            sum by (namespace, route) (rate(http_requests_total{namespace="shop", code=~"5.."}[5m]))
            /
            sum by (namespace, route) (rate(http_requests_total{namespace="shop"}[5m]))
        - record: route:http_request_duration_seconds:p99_5m
          expr: |
            histogram_quantile(0.99,
              sum by (namespace, route, le) (rate(http_request_duration_seconds_bucket{namespace="shop"}[5m])))
        - alert: OrdersAPIHighErrorRate
          expr: route:http_request_errors:ratio_rate5m > 0.05
          for: 5m
          labels:
            severity: critical
          annotations:
            summary: "{{ $labels.route }} returns 5xx for {{ $value | humanizePercentage }} of requests"
            runbook_url: https://runbooks.example.com/orders-api#high-error-rate
        - alert: OrdersAPILatencyHigh
          expr: route:http_request_duration_seconds:p99_5m > 0.5
          for: 10m
          labels:
            severity: warning
          annotations:
            summary: "p99 latency of {{ $labels.route }} is {{ $value | humanizeDuration }}"
            runbook_url: https://runbooks.example.com/orders-api#latency
        - alert: OrdersAPITargetDown
          expr: up{namespace="shop"} == 0
          for: 5m
          labels:
            severity: warning
          annotations:
            summary: "Prometheus cannot scrape {{ $labels.pod }} ({{ $labels.instance }})"
    - name: kubernetes.workloads
      rules:
        - alert: PodCrashLooping
          expr: max_over_time(kube_pod_container_status_waiting_reason{reason="CrashLoopBackOff"}[5m]) >= 1
          for: 15m
          labels:
            severity: warning
          annotations:
            summary: "{{ $labels.namespace }}/{{ $labels.pod }} ({{ $labels.container }}) is in CrashLoopBackOff"
            runbook_url: https://runbooks.example.com/k8s#crashloopbackoff
        - alert: ContainerOOMKilled
          expr: |
            increase(kube_pod_container_status_restarts_total[15m]) > 0
            and on (namespace, pod, container)
            kube_pod_container_status_last_terminated_reason{reason="OOMKilled"} == 1
          labels:
            severity: warning
          annotations:
            summary: "{{ $labels.namespace }}/{{ $labels.pod }} ({{ $labels.container }}) was OOMKilled (exit code 137)"
            runbook_url: https://runbooks.example.com/k8s#oomkilled
        - alert: ContainerCannotStart
          expr: kube_pod_container_status_waiting_reason{reason=~"ImagePullBackOff|ErrImagePull|CreateContainerConfigError|InvalidImageName"} == 1
          for: 10m
          labels:
            severity: warning
          annotations:
            summary: "{{ $labels.namespace }}/{{ $labels.pod }} waits with {{ $labels.reason }}"
            runbook_url: https://runbooks.example.com/k8s#cannot-start
        - alert: PodNotRunning
          expr: sum by (namespace, pod) (kube_pod_status_phase{phase=~"Pending|Unknown|Failed"}) > 0
          for: 15m
          labels:
            severity: warning
          annotations:
            summary: "{{ $labels.namespace }}/{{ $labels.pod }} has not been Running for 15 minutes"
        - alert: CPUThrottlingHigh
          expr: |
            sum by (namespace, pod, container) (increase(container_cpu_cfs_throttled_periods_total{container!=""}[5m]))
            /
            sum by (namespace, pod, container) (increase(container_cpu_cfs_periods_total{container!=""}[5m]))
            > 0.25
          for: 15m
          labels:
            severity: info
          annotations:
            summary: "{{ $labels.container }} in {{ $labels.namespace }}/{{ $labels.pod }} is throttled in {{ $value | humanizePercentage }} of CFS periods"
        - alert: ContainerMemoryNearLimit
          expr: |
            max by (namespace, pod, container) (container_memory_working_set_bytes{container!=""})
            /
            max by (namespace, pod, container) (kube_pod_container_resource_limits{resource="memory"})
            > 0.9
          for: 15m
          labels:
            severity: warning
          annotations:
            summary: "{{ $labels.container }} uses {{ $value | humanizePercentage }} of its memory limit"
        - alert: PVCPending
          expr: kube_persistentvolumeclaim_status_phase{phase="Pending"} == 1
          for: 10m
          labels:
            severity: warning
          annotations:
            summary: "PVC {{ $labels.namespace }}/{{ $labels.persistentvolumeclaim }} is Pending"
    - name: kubernetes.nodes
      rules:
        - alert: NodeNotReady
          expr: kube_node_status_condition{condition="Ready", status="true"} == 0
          for: 5m
          labels:
            severity: critical
          annotations:
            summary: "Node {{ $labels.node }} is not Ready"
            runbook_url: https://runbooks.example.com/k8s#nodenotready
        - alert: NodePressure
          expr: kube_node_status_condition{condition=~"MemoryPressure|DiskPressure|PIDPressure", status="true"} == 1
          for: 5m
          labels:
            severity: warning
          annotations:
            summary: "Node {{ $labels.node }} reports {{ $labels.condition }}; the kubelet may evict Pods"
yaml
# AlertmanagerConfig (v1alpha1): a namespaced slice of Alertmanager routing.
# With the operator's default matcher strategy (OnNamespace) its routes AND
# inhibition rules only see alerts whose namespace label is "shop". Cluster-
# wide inhibition (NodeNotReady muting Pod alerts) therefore belongs in the
# global Alertmanager configuration, not here.
apiVersion: monitoring.coreos.com/v1alpha1
kind: AlertmanagerConfig
metadata:
  name: shop-oncall
  namespace: shop
  labels:
    alertmanagerConfig: shop
spec:
  route:
    receiver: shop-slack
    groupBy: [alertname, namespace]
    groupWait: 30s
    groupInterval: 5m
    repeatInterval: 4h
    routes:
      - receiver: shop-pager
        matchers:
          - name: severity
            value: critical
            matchType: "="
  receivers:
    - name: shop-slack
      slackConfigs:
        - apiURL:
            name: alertmanager-slack     # Secret in the same namespace
            key: webhook-url
          channel: "#shop-alerts"
          sendResolved: true
    - name: shop-pager
      webhookConfigs:
        - url: https://pager.example.com/hooks/alertmanager
          sendResolved: true
yaml
# Helm values for kube-prometheus-stack (chart 94.2.1, operator v0.95.2).
# helm install kube-prometheus-stack \
#   oci://ghcr.io/prometheus-community/charts/kube-prometheus-stack \
#   --namespace monitoring --create-namespace -f kube-prometheus-stack-values.yaml
prometheus:
  prometheusSpec:
    retention: 15d
    retentionSize: 40GiB
    # true (the default) = only pick up ServiceMonitors/PodMonitors/rules that
    # carry the label release: <release name>. Keep it, and label your objects.
    serviceMonitorSelectorNilUsesHelmValues: true
    podMonitorSelectorNilUsesHelmValues: true
    ruleSelectorNilUsesHelmValues: true
    # Look for those objects in every namespace, not just "monitoring".
    serviceMonitorNamespaceSelector: {}
    podMonitorNamespaceSelector: {}
    ruleNamespaceSelector: {}
    # No storageClassName: the PVC uses the cluster's default StorageClass
    # (kind: "standard"; set gp3, premium-rwo, ... explicitly on a cloud).
    storageSpec:
      volumeClaimTemplate:
        spec:
          accessModes: [ReadWriteOnce]
          resources:
            requests:
              storage: 50Gi
alertmanager:
  alertmanagerSpec:
    alertmanagerConfigSelector:
      matchLabels:
        alertmanagerConfig: shop
    alertmanagerConfigNamespaceSelector: {}
grafana:
  admin:                     # create first: kubectl -n monitoring create secret generic grafana-admin ...
    existingSecret: grafana-admin
    userKey: admin-user
    passwordKey: admin-password
kubeStateMetrics:
  enabled: true
nodeExporter:
  enabled: true

Dashboards and key signals: Grafana, USE method, RED method Must-know ​

In plain words: For every resource (node CPU, memory, disk, a container's CPU quota) ask how busy it is, how much work is waiting, and how many errors it has. For every service ask how many requests, how many fail, and how long they take. The first is USE, the second is RED.

Common misunderstanding: "High CPU means the service is slow." A container can be at 40 % of its CPU limit on average and still be throttled in a third of its 100 ms CFS periods, which shows up as latency, not as high average CPU. And a node at 95 % CPU with good RED numbers is efficient, not broken. Grafana's own guide: "The USE method tells you how happy your machines are, the RED method tells you how happy your users are", and "alerting should be done on RED dashboards".

Definition: USE (Brendan Gregg): "For every resource, check utilization, saturation, and errors." RED (Tom Wilkie): Rate ("Requests per second"), Errors ("Number of requests that are failing"), Duration ("distribution of latency measurements"). Grafana is the dashboard and exploration UI for Prometheus, Loki and Tempo; kube-prometheus-stack provisions "a collection of curated Grafana dashboards that are automatically loaded into Grafana via ConfigMaps".

LevelMethodSignalPromQL (Prometheus with kube-state-metrics and cAdvisor)
ServiceRED rateRequests per second per routesum by (route) (rate(http_requests_total[5m]))
ServiceRED errors5xx ratioroute:http_request_errors:ratio_rate5m (recording rule in the snippet)
ServiceRED durationp99 latencyhistogram_quantile(0.99, sum by (route, le) (rate(http_request_duration_seconds_bucket[5m])))
ContainerUSE utilizationCPU usedrate(container_cpu_usage_seconds_total{container!=""}[5m])
ContainerUSE saturationCPU throttled shareincrease(container_cpu_cfs_throttled_periods_total[5m]) / increase(container_cpu_cfs_periods_total[5m])
ContainerUSE utilizationMemory against limitcontainer_memory_working_set_bytes / on(namespace,pod,container) kube_pod_container_resource_limits{resource="memory"}
ContainerUSE errorsOOM kills, restartscontainer_oom_events_total, kube_pod_container_status_restarts_total
NodeUSE utilizationCPU busy1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))
NodeUSE saturationPressure conditionskube_node_status_condition{condition=~".*Pressure",status="true"}
ClusterStatePods not runningsum by (namespace) (kube_pod_status_phase{phase!~"Running|Succeeded"})
text
Sequence: reading a latency incident with RED then USE
1  RED: p99 of /orders/{id} from 80 ms to 900 ms, errors flat, rate flat
2  USE (container): throttled periods 0.02 -> 0.45 after the deploy
3  diff: the new release set limits.cpu: 500m (was 2)
4  fix: raise or remove the CPU limit; keep the request (see the Resources chapter)

Real scenarios: latency spikes every minute caused by CPU throttling during GC; a "memory leak" that is page cache (working set rises with file reads and falls under pressure); a dashboard per node that nobody reads, replaced by one RED row per service with USE drill-downs.

Fix / how to use it: one RED row per service (rate and errors left, latency right, as Grafana's guide suggests), USE dashboards for nodes and containers from the chart, template variables instead of a dashboard per namespace, and alerts only on the RED recording rules plus a handful of state alerts.

Log and trace pipelines: OpenTelemetry Collector, Fluent Bit, Vector, Loki, Tempo Important ​

In plain words: A node agent runs on every node, reads every container's log file, adds "which Pod, which namespace, which labels", and ships the lines to a store. Traces go from the app's SDK to a collector and on to a trace store. Grafana links the two by trace id.

Common misunderstanding: "The collector should run as a Deployment with three replicas for HA." Receivers that read the whole cluster (k8s_cluster, k8sobjects for Events) must run once; the OpenTelemetry docs mark them "Yes, but more than one replica results in duplicate data". Receivers that read node-local data (filelog, kubeletstats, host metrics) belong in a DaemonSet, because as a Deployment they "only collect ... from the node it is deployed on". That is the whole DaemonSet vs Deployment collector rule.

Definition: the Kubernetes logging docs describe three cluster-level patterns: a node-level logging agent ("recommended to run the agent as a DaemonSet", needs no application change), a sidecar container (streaming a file to its own stdout, or running its own agent), and pushing directly from the application ("outside the scope of Kubernetes"). The tools:

ToolRoleKubernetes specifics
OpenTelemetry CollectorReceives, processes and exports logs, metrics, tracesAgent (DaemonSet): filelog, kubeletstats, OTLP from local Pods, k8sattributes processor; gateway (Deployment): k8s_cluster, k8sobjects, tail sampling, export. Helm presets: logsCollection, kubernetesAttributes, kubeletMetrics, clusterMetrics, kubernetesEvents
Fluent BitLightweight log agent (C)DaemonSet via the Helm chart; tail input on /var/log/containers/*.log with multiline.parser docker, cri; kubernetes filter with Merge_Log (parse JSON lines into fields) and pod annotations fluentbit.io/exclude, fluentbit.io/parser
VectorLog and metrics pipeline (Rust)kubernetes_logs source "Collects Pod logs" from its host node, enriched via the Kubernetes API
LokiLog store"does not index the contents of the logs, but only indexes metadata about your logs as a set of labels"; chunks in object storage; accepts OTLP at /otlp
TempoTrace store"open-source, easy-to-use, and high-scale distributed tracing backend"; TraceQL
Grafana Alloy, PromtailGrafana's agentsSame DaemonSet pattern (Promtail is the older Loki agent)
text
Sequence: one request, three signals, one id
1  orders-api receives GET /orders/42 with traceparent 00-4bf9...-00f0...-01
2  slog line {"msg":"request","correlation_id":"abc-123","trace_id":"4bf9..."} -> stdout
3  containerd -> /var/log/pods/shop_orders-api-7d9c_<uid>/orders-api/0.log
4  Fluent Bit / OTel agent tails it, adds k8s.namespace.name=shop, k8s.pod.name=...
5  Loki stores it under labels {namespace="shop", app="orders-api"}; trace_id as structured metadata
6  the app's OTel SDK sent the span to the agent :4318 -> gateway -> Tempo
7  Grafana: alert -> RED panel -> exemplar or LogQL |= "trace_id" -> the trace in Tempo

Real scenarios: a Loki cluster falling over because someone made pod or request_id a stream label (Loki's guidance: labels with "low cardinality, ideally limited to tens of values"; never "a label which can have unbounded or infinite values"); a collector feeding its own debug output back into its logs pipeline (the Helm docs warn about a "log explosion" and exclude the collector's own logs by default); double-counted Events after scaling the gateway to three replicas.

PatternProsCons
Node agent (DaemonSet)One agent per node, no app change, works with kubectl logsNeeds host path access; one config for all apps
Sidecar streaming to stdoutLets a legacy app that writes files appear in kubectl logsOne extra container per Pod
Sidecar running an agentPer-app configResource cost per Pod; bypasses kubectl logs
App pushes directly (OTLP logs, vendor SDK)Rich structure, no file parsingLost logs if the backend is down; outside Kubernetes

Fix / how to use it: an OpenTelemetry agent DaemonSet plus a single-replica gateway, or Fluent Bit for logs only, with low-cardinality labels:

yaml
# OpenTelemetry Collector Helm chart, AGENT tier: one collector per node.
# helm repo add open-telemetry https://open-telemetry.github.io/opentelemetry-helm-charts
# helm install otel-agent open-telemetry/opentelemetry-collector \
#   --namespace observability -f otel-agent-values.yaml
mode: daemonset
image:
  repository: otel/opentelemetry-collector-k8s
presets:
  logsCollection:            # filelog receiver on /var/log/pods/*/*/*.log
    enabled: true
  kubernetesAttributes:      # k8sattributes processor: k8s.pod.name, k8s.namespace.name, ...
    enabled: true
  kubeletMetrics:            # kubeletstats receiver: this node's pod/container usage
    enabled: true
config:
  receivers:
    otlp:                    # apps send traces/metrics/logs to the agent on their node
      protocols:
        grpc:
          endpoint: 0.0.0.0:4317
        http:
          endpoint: 0.0.0.0:4318
  exporters:
    otlp_http:
      endpoint: http://otel-gateway-opentelemetry-collector.observability.svc:4318
  service:
    pipelines:
      traces:
        receivers: [otlp]
        exporters: [otlp_http]
      metrics:
        exporters: [otlp_http]
      logs:
        exporters: [otlp_http]
yaml
# OpenTelemetry Collector Helm chart, GATEWAY tier: cluster-wide receivers
# that must run exactly once (a second replica would duplicate every point).
# helm install otel-gateway open-telemetry/opentelemetry-collector \
#   --namespace observability -f otel-gateway-values.yaml
mode: deployment
replicaCount: 1
image:
  repository: otel/opentelemetry-collector-k8s
presets:
  clusterMetrics:            # k8s_cluster receiver: pod phases, node conditions
    enabled: true
  kubernetesEvents:          # k8sobjects receiver watching Events -> logs pipeline
    enabled: true
config:
  receivers:
    otlp:
      protocols:
        http:
          endpoint: 0.0.0.0:4318
  exporters:
    otlp_http/tempo:         # traces
      endpoint: http://tempo.observability.svc:4318
    otlp_http/loki:          # logs (Loki accepts OTLP on /otlp)
      endpoint: http://loki-gateway.observability.svc/otlp
    otlp_http/metrics:       # any OTLP-capable metrics store (placeholder name)
      endpoint: http://metrics-backend.observability.svc:4318
  service:
    pipelines:
      traces:
        receivers: [otlp]
        exporters: [otlp_http/tempo]
      metrics:               # the clusterMetrics preset appends k8s_cluster here
        receivers: [otlp]
        exporters: [otlp_http/metrics]
      logs:                  # the kubernetesEvents preset appends k8sobjects here
        receivers: [otlp]
        exporters: [otlp_http/loki]
yaml
# Fluent Bit Helm chart (fluent/fluent-bit), deployed as a DaemonSet.
# The chart's default [INPUT] already tails /var/log/containers/*.log with
# "multiline.parser docker, cri"; this file replaces the filter and output.
# helm repo add fluent https://fluent.github.io/helm-charts
# helm install fluent-bit fluent/fluent-bit -n observability -f fluent-bit-values.yaml
config:
  filters: |
    [FILTER]
        Name                kubernetes
        Match               kube.*
        Merge_Log           On
        Keep_Log            Off
        K8S-Logging.Parser  On
        K8S-Logging.Exclude On

  outputs: |
    [OUTPUT]
        Name        loki
        Match       kube.*
        Host        loki-gateway.observability.svc
        Port        80
        # Low-cardinality stream labels only: never pod UID, request id, user id.
        Labels      job=fluent-bit, namespace=$kubernetes['namespace_name'], app=$kubernetes['labels']['app.kubernetes.io/name']
        # High-cardinality fields stay searchable without becoming streams.
        Structured_Metadata pod=$kubernetes['pod_name'], correlation_id=$correlation_id
        Line_Format json

The exporter name is otlp_http: the collector's README says "The otlphttp deprecated alias exists for the component name. It will be removed in a future version", so older guides that write otlphttp still work today but should be updated.

Where a log line goes: stdout -> runtime file -> kubelet (kubectl logs) or node agent -> backendNodecontainer processJSON line to stdout/stderr+ correlation_id, trace_idcontainerd (CRI) writes/var/log/pods/ns_pod_uid/c/0.logRFC3339Nano stdout F msgkubelet rotates the filecontainerLogMaxSize 10Mi x 5 fileskubectl logsreads newest file onlyvia kubelet APInode agent (DaemonSet)Fluent Bit / Vector / OTel filelogtails /var/log/containers/*.log,adds pod, namespace, labelsLokiindexes labels only,chunks in objectstorage (S3, GCS)Events (API server)k8sobjects receiver,event exporterTracesapp OTel SDKOTLP gRPC :4317 / HTTP :4318OTel agent (DaemonSet)k8sattributes processorOTel gateway(Deployment, 1 replicafor cluster receivers)Tempotrace storeGrafanalogs -> trace bytrace_id; trace -> logsby correlation_idNot shown: the sidecar pattern (a second container tails a file the app writes) and pushing logs from the app directly.Both bypass kubectl logs; prefer stdout plus one node agent unless the app cannot write to stdout.

Pending and FailedScheduling Must-know ​

In plain words: Pending is the Pod phase from acceptance until every container is set up: it covers waiting to be scheduled and, after scheduling, the time spent pulling images and creating containers. When the Pod has no node yet, the scheduler writes the reason into a FailedScheduling Warning event; this block is about that case.

Common misunderstanding: "Pending always means a scheduling problem." The Pod lifecycle page defines Pending to include "the time a Pod spends waiting to be scheduled as well as the time spent downloading container images over the network". The STATUS column of kubectl get pods is not the phase: it shows a container waiting reason when there is one (ContainerCreating, ErrImagePull, ImagePullBackOff, CreateContainerConfigError) while the phase is still Pending. So split by node: NODE <none> in kubectl get pods -o wide is a scheduling problem; a Pod with a node that is still Pending is a kubelet-side problem (image, volume, sandbox, config).

Definition: the scheduler's message has the shape "0/X nodes are available: PreFilterMsg. FilterMsg. PostFilterMsg." Each plugin contributes counted reasons, for example Insufficient cpu, Insufficient memory, Too many pods (resource fit), node(s) had untolerated taint(s), node(s) didn't match Pod's node affinity/selector, and pod has unbound immediate PersistentVolumeClaims (volume binding). The Kubernetes debugging guide names the usual causes: not enough resources (delete Pods, adjust requests, or add nodes) and hostPort, which limits the Pod to one per node.

text
Sequence: a request nobody can satisfy
1  Deployment orders-api scaled to 6, each Pod requests cpu: 2
2  scheduler event: FailedScheduling  0/3 nodes are available: 3 Insufficient cpu. ...
3  Pod stays Pending; cluster autoscaler (if any) sees an unschedulable Pod and adds a node
4  new node Ready -> scheduler binds -> kubelet starts the Pod

Real scenarios: requests copied from a laptop benchmark (cpu: 4) on 2-vCPU nodes; a GPU Pod whose node pool is tainted and the toleration was forgotten; nodeSelector on a zone label that does not exist in a new region; a StatefulSet Pod waiting for a PVC whose StorageClass uses Immediate binding in another zone; Pod anti-affinity requiring more nodes than exist.

Reason in the eventCauseFix
Insufficient cpu / memoryRequests larger than free allocatableLower requests, add nodes, enable an autoscaler
Too many podsNode maxPods reachedMore nodes, or raise maxPods within CNI limits
node(s) had untolerated taint(s)Taint without matching tolerationAdd the toleration, or schedule elsewhere
node(s) didn't match Pod's node affinity/selectorLabel mismatchFix the selector or the node labels
pod has unbound immediate PersistentVolumeClaimsPVC not boundPVC Pending
didn't have free ports for the requested pod portshostPort conflictUse a Service instead of hostPort

Fix / how to use it: read the event first (kubectl events --for pod/NAME), alert on kube_pod_status_unschedulable or kube_pod_status_phase{phase="Pending"} for more than 15 minutes, and see Resources, Scheduling & Autoscaling for requests, taints, affinity and preemption.

Cannot start: ImagePullBackOff, ErrImagePull, CreateContainerConfigError Must-know ​

In plain words: The Pod has a node, but the kubelet cannot create the container: either it cannot get the image, or the container's configuration refers to something that does not exist.

Common misunderstanding: "ImagePullBackOff means the registry is down." It means the last pull failed and the kubelet is waiting before the next try. The cause is usually on your side: "invalid image name, or pulling from a private registry without imagePullSecret", and Kubernetes "raises the delay between each attempt until it reaches a compiled-in limit, which is 300 seconds (5 minutes)".

Definition: these are container waiting reasons, defined as error values in the kubelet source: ErrImagePull (a pull attempt failed), ImagePullBackOff (back-off between attempts), InvalidImageName, ErrImageNeverPull (imagePullPolicy: Never and the image is not on the node), and CreateContainerConfigError (the kubelet failed to build the container config, typically because an env var or volume refers to a ConfigMap or Secret, or a key in one, that does not exist). Related: RunContainerError (the runtime could not start the process, for example a bad command), CreateContainerError.

text
Sequence: a typo in a Secret key
1  Deployment env: DB_PASSWORD from secretKeyRef {name: shop-db, key: pasword}
2  kubelet: generate container config -> key "pasword" not found in Secret shop-db
3  STATUS CreateContainerConfigError; Event Warning Failed: Error: couldn't find key pasword in Secret shop/shop-db
4  fix the key (or create it); the kubelet retries automatically, no restart needed

Real scenarios: a tag that was never pushed because CI failed after the manifest was updated; a private GHCR image with no imagePullSecrets in a new namespace; Docker Hub pull limits on a shared NAT IP; an ARM node pulling an amd64-only image (pull succeeds, then exec format error and CrashLoopBackOff); a Secret created by External Secrets Operator a minute after the Deployment (resolves itself after a retry); CreateContainerConfigError from runAsNonRoot with an image whose user is root.

Waiting reasonLook atUsual fix
ErrImagePull → ImagePullBackOffEvent message: not found, unauthorized, toomanyrequests, TLSFix tag/digest, add imagePullSecrets, mirror the image
InvalidImageNameThe image stringRemove spaces/uppercase, fix the registry host
ErrImageNeverPullimagePullPolicy: NeverUse IfNotPresent, or preload the image
CreateContainerConfigErrorEvent message names the ConfigMap/Secret/keyCreate it, fix the key, or mark it optional: true
RunContainerErrorEvent message from the runtimeFix command/args, the binary path, permissions

Fix / how to use it: pin images by digest in production (see Images & Dockerfiles), alert on kube_pod_container_status_waiting_reason{reason=~"ImagePullBackOff|ErrImagePull|CreateContainerConfigError"} for 10 minutes (the ContainerCannotStart rule in the snippet), and keep Secrets and Deployments in the same release so a missing key fails the rollout, not production traffic.

CrashLoopBackOff and exit codes Must-know ​

In plain words: The container starts, exits, and is restarted, again and again; between attempts the kubelet waits longer each time. CrashLoopBackOff is the waiting period, not the error.

Common misunderstanding: "CrashLoopBackOff is a Kubernetes error." It is the kubelet protecting the node from a process that keeps dying. The Pod lifecycle page lists the causes: application errors, configuration errors, resource constraints, health checks failing, and liveness or startup probes returning Failure.

Definition: after an exit, the kubelet restarts the container according to restartPolicy "with an exponential backoff delay (10s, 20s, 40s, …), that is capped at 300 seconds (5 minutes). Once a container has executed for 10 minutes without any problems, the kubelet resets the restart backoff timer". (Alpha feature gates ReduceDefaultCrashLoopBackOffDecay and KubeletCrashLoopBackOffMax change those numbers.) kubectl describe shows Last State: Terminated with Reason and Exit Code; the termination message (file terminationMessagePath, truncated at 4096 bytes, or the last 2048 bytes or 80 lines of the log with terminationMessagePolicy: FallbackToLogsOnError) is the fastest clue.

Exit codeMeaningTypical cause
0Clean exitThe process is not a server (wrong command), or a Job finished under a Deployment
1Generic errorUncaught exception, config validation failed
2Go: unrecovered panic (runtime exit status 2), or shell misusepanic: runtime error: invalid memory address
126 / 127Not executable / not foundWrong command, missing binary, wrong architecture script
137128 + 9 (SIGKILL)OOMKilled at the memory limit, or killed after the grace period (liveness failure, eviction)
139128 + 11 (SIGSEGV)Native crash (cgo, PHP extension)
143128 + 15 (SIGTERM)Stopped normally but did not exit 0 on SIGTERM
text
Sequence: the back-off schedule for a container that dies after 2 s
t=0     start #1, exit 1 at t=2
t=2     restart immediately (#2), exit at t=4
t=14    back-off 10 s, start #3 ... exit
t=36    back-off 20 s ...
t=78    back-off 40 s ... then 80 s, 160 s, 300 s, 300 s, ...
        STATUS shows CrashLoopBackOff while waiting; RESTARTS keeps counting
        runs of 10 minutes without a crash reset the back-off

Real scenarios: a missing env var after a refactor (exit 1, log line says so); a liveness probe on a slow-starting JVM or Laravel Octane worker (exit 137 with Liveness probe failed events; fix with a startup probe); migrations in the entrypoint failing because the database is not reachable yet; a container that runs php artisan migrate and exits 0 under a Deployment.

Fix / how to use it: kubectl logs --previous, then kubectl describe for exit code and probe events; set terminationMessagePolicy: FallbackToLogsOnError (the Go Deployment in the snippets does); if the process dies too fast to inspect, kubectl debug POD -it --copy-to=POD-debug --container=app -- sh and run the command by hand; alert on PodCrashLooping (snippet) rather than on restarts alone.

OOMKilled, exit code 137, and resource saturation Must-know ​

In plain words: A container that uses more memory than its limit is killed by the kernel and restarted; Kubernetes records OOMKilled and exit code 137. The same reason appears when the whole node runs out of memory faster than the kubelet can evict, and the kernel picks a victim by OOM score. A container that wants more CPU than its limit is not killed, it is slowed down (throttled).

Common misunderstanding: "My container was OOMKilled, but its memory graph never reached the limit." Scrape intervals (15–30 s) miss a spike that lasts a second, and the graph you looked at may be RSS rather than the working set. The OOM decision is made on the cgroup's memory, so watch container_memory_working_set_bytes against the limit and container_oom_events_total.

Definition: the Kubernetes task page: "If the Container continues to consume memory beyond its limit, the Container is terminated", and its example shows exitCode: 137, reason: OOMKilled. Node-level memory shortage has two outcomes. Normally the kubelet evicts Pods when memory.available falls below the eviction threshold (see Node problems) and the Pod's status shows Evicted. But "If the node experiences an out of memory (OOM) event prior to the kubelet being able to reclaim memory, the node depends on the oom_killer": the kubelet sets oom_score_adj by QoS (Guaranteed -997, BestEffort 1000, Burstable in between) and the kernel "kills the container with the highest score", which is also recorded as OOMKilled although that container may have been below its own limit. Check node memory and the container's working set against its limit before concluding which one happened. CPU limits are enforced with CFS quota: in each period (100 ms by default) a container may run for its quota; when it is used up the container waits for the next period, counted in container_cpu_cfs_throttled_periods_total and container_cpu_cfs_throttled_seconds_total.

text
Sequence: a PHP worker leaking memory
1  queue worker limit 512Mi; each job leaves 8 MiB behind
2  working set 120 -> 480 MiB over 45 jobs; container_memory_working_set_bytes / limit = 0.94
3  job 50: allocation crosses 512Mi -> kernel OOM killer -> exit 137, Last State OOMKilled
4  restart; RESTARTS 1; ContainerOOMKilled alert fires (restart + last reason OOMKilled)
5  fix: queue:work --max-jobs=500 --memory=400 (exit before the limit), or fix the leak

Real scenarios: a Go service with a cache that has no size bound; a JVM whose heap is sized for the node, not the limit; image resizing in a Laravel queue job; a sidecar (Istio, log agent) without limits OOMKilling the Pod's main container's neighbours; CPU throttling causing p99 latency spikes with average CPU at 30 %.

SignalSeries or fieldRead as
OOM killlastState.terminated.reason=OOMKilled, exit 137At the limit: raise it or fix the usage; node-wide OOM: fix requests and node sizing
Near the limitcontainer_memory_working_set_bytes / limit > 0.9Early warning (ContainerMemoryNearLimit)
Kernel OOM eventscontainer_oom_events_totalAlso catches OOM of a child process that did not kill PID 1
CPU throttlingthrottled_periods / periods > 0.25Limit too low for bursts (CPUThrottlingHigh, info only)
Node memory pressureMemoryPressure=True, Pods EvictedRequests too low across the node

Fix / how to use it: set memory limits from measured working set plus headroom, keep requests honest so the scheduler does not overpack nodes, prefer no CPU limit (or a generous one) for latency-sensitive services, and see Resources, Scheduling & Autoscaling for QoS classes and the CFS mechanics.

Readiness probe failing: Running but not Ready Important ​

In plain words: The process is up, but its readiness probe says "do not send me traffic", so the Pod is removed from the Service's endpoints. Users see errors only if every Pod is not ready.

Common misunderstanding: "Readiness should check the database." If every Pod's readiness depends on one shared dependency, a database blip removes all Pods from the Service at once and turns a partial outage into a full one. Readiness should say "this Pod can serve"; dependency health belongs in metrics and alerts.

Definition: the kubelet runs the probe; on failure it records a Warning event with reason Unhealthy and the message "Readiness probe failed: ..." (for HTTP probes, "HTTP probe failed with statuscode: 503"); the EndpointSlice marks the endpoint not ready and kube-proxy and Ingress controllers stop routing to it. A failing liveness probe restarts the container (exit 137 after the grace period); a failing startup probe does the same before the other probes start. Probe tuning is owned by Kubernetes Workloads.

text
Sequence: a rollout that never finishes
1  new ReplicaSet Pods Running 0/1; old Pods still serve (maxUnavailable 0)
2  Events: Warning Unhealthy  Readiness probe failed: HTTP probe failed with statuscode: 503
3  kubectl exec / debug: curl localhost:9090/readyz -> "not ready" (app waits for a migration lock)
4  kubectl rollout status deploy/orders-api -> waiting; progressDeadlineSeconds -> ProgressDeadlineExceeded

Real scenarios: the probe points at port 8080 but the app moved its health endpoint to the admin port 9090; timeoutSeconds: 1 on an endpoint that takes 1.2 s under load; readiness checking Redis, so a Redis failover empties the Service; Laravel /up returning 500 because APP_KEY is missing.

Fix / how to use it: probe a cheap local endpoint on the admin port (on SIGTERM the Go service turns /readyz to 503 and keeps serving for SHUTDOWN_DELAY before closing, so traffic still in flight towards it is answered), set timeoutSeconds and failureThreshold from measured latency, and alert on kube_deployment_status_replicas_unavailable or a stalled rollout, not on single probe failures.

yaml
# The Go orders API with two named ports: "http" for traffic (the Ingress
# routes here) and "metrics" for /metrics and the probes (only Prometheus and
# the kubelet use it). The ServiceMonitor selects the Service by label and
# scrapes the port by NAME.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
  namespace: shop
  labels:
    app.kubernetes.io/name: orders-api
spec:
  replicas: 3
  selector:
    matchLabels:
      app.kubernetes.io/name: orders-api
  template:
    metadata:
      labels:
        app.kubernetes.io/name: orders-api
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: orders-api
          image: ghcr.io/example/orders-api:1.4.2
          env:
            - name: APP_ADDR
              value: ":8080"
            - name: METRICS_ADDR
              value: ":9090"
            - name: SHUTDOWN_DELAY     # readiness off -> wait -> Shutdown(8s); 5s + 8s < 30s grace
              value: "5s"
          ports:
            - name: http
              containerPort: 8080
            - name: metrics
              containerPort: 9090
          readinessProbe:
            httpGet:
              path: /readyz
              port: metrics
            periodSeconds: 5
            failureThreshold: 3
          livenessProbe:
            httpGet:
              path: /healthz
              port: metrics
            periodSeconds: 10
            failureThreshold: 3
          resources:
            requests:
              cpu: 250m
              memory: 128Mi
            limits:
              memory: 256Mi
          # Kubernetes reads this file (or the log tail) into the
          # container status when the process dies.
          terminationMessagePolicy: FallbackToLogsOnError
---
apiVersion: v1
kind: Service
metadata:
  name: orders-api
  namespace: shop
  labels:
    app.kubernetes.io/name: orders-api
spec:
  selector:
    app.kubernetes.io/name: orders-api   # must match the Pod labels exactly
  ports:
    - name: http
      port: 80
      targetPort: http
    - name: metrics
      port: 9090
      targetPort: metrics

Terminating stuck and finalizers Important ​

In plain words: Deleting an object only sets a deletion timestamp; it disappears when every finalizer listed on it has been removed by the controller that owns it. If that controller is gone or failing, the object waits forever in Terminating.

Common misunderstanding: "Force-delete fixes Terminating." Deletion with finalizers "Prevents the object from being removed until all items are removed from its metadata.finalizers field", and --force --grace-period=0 does not remove finalizers: an object that is stuck on a finalizer stays stuck. For a Pod without finalizers, force deletion removes the API object without waiting for the kubelet to confirm, so the process may still be running on the node (dangerous for StatefulSets that assume one Pod per identity). The only way past a finalizer is to let its controller finish or to remove the finalizer by hand, which skips the cleanup it guards (a cloud load balancer, a volume, a DNS record).

Definition: "If a Pod is stuck in the Terminating state, it means that a deletion has been issued for the Pod, but the control plane is unable to delete the Pod object. This typically happens if the Pod has a finalizer and there is an admission webhook installed in the cluster that prevents the control plane from removing the finalizer." The docs' check: look for ValidatingWebhookConfiguration or MutatingWebhookConfiguration that target UPDATE on Pods. Kube-state-metrics exposes kube_pod_deletion_timestamp, and the Kubernetes docs show an alert for Pods "blocked in Terminating state" for more than 5 minutes.

text
Sequence: a namespace that will not go away
1  kubectl delete namespace preview-123          -> Terminating
2  kubectl get namespace preview-123 -o yaml     -> status.conditions say content or finalizers remain
3  kubectl api-resources --verbs=list --namespaced -o name \
     | xargs -n1 kubectl get -n preview-123 --ignore-not-found
                                                 -> one Certificate with finalizer of a removed operator
4  reinstall the operator (preferred) or patch the finalizer away, accepting the skipped cleanup

Real scenarios: a PVC stuck in Terminating because a Pod still mounts it (kubernetes.io/pvc-protection); a Service of type LoadBalancer waiting for the cloud controller to delete the load balancer; custom resources whose operator was uninstalled first; Pods on a node that is gone (the kubelet can never confirm; the node controller handles them after the node is deleted).

Fix / how to use it: find the finalizer (kubectl get OBJ -o jsonpath='{.metadata.finalizers}'), find the controller that owns it and fix that; uninstall operators after their custom resources; force-delete Pods (without finalizers) only when you know the node is gone.

Node problems: Evicted, node pressure, NodeNotReady Must-know ​

In plain words: When a node runs low on memory, disk or process IDs, its kubelet evicts Pods to save itself. When a node stops reporting, the control plane marks it NotReady/Unknown and, after a delay, moves its Pods elsewhere.

Common misunderstanding: "Evicted Pods are a scheduler problem." Eviction is the kubelet acting on node pressure (MemoryPressure, DiskPressure, PIDPressure), usually because requests were too low and the node was overcommitted, or because logs and images filled the disk.

Definition: node-pressure eviction uses signals such as memory.available, nodefs.available, nodefs.inodesFree, imagefs.available; the kubelet's default hard eviction thresholds are memory.available<100Mi (Linux), nodefs.available<10%, imagefs.available<15% and nodefs.inodesFree<5%, and for hard thresholds it uses a 0s grace period. Nodes heartbeat through .status updates and a Lease in kube-node-lease; the node controller sets Ready to Unknown when a node becomes unreachable (kube-controller-manager --node-monitor-grace-period, default 50s) and "waits 5 minutes between marking the node as Unknown and submitting the first eviction request". kubectl describe node then shows conditions with reason NodeStatusUnknown and message "Kubelet stopped posting node status".

text
Sequence: a node that dies at 14:00
14:00:00  kubelet stops (kernel panic, network partition)
14:00:50  node controller: Ready=Unknown ("Kubelet stopped posting node status"); NodeNotReady event
14:00:50  taint node.kubernetes.io/unreachable:NoExecute added
14:05:50  Pods' default toleration (300 s) expires -> evicted -> controllers create replacements
          StatefulSet Pods wait: the old Pod is not confirmed gone (no double identity)

Real scenarios: a node at DiskPressure because container logs and unused images filled /var; PIDPressure from a fork bomb in a CI runner Pod; a whole node pool NotReady after a CNI DaemonSet upgrade failed; kubelet certificate expiry; memory pressure from BestEffort Pods without requests.

ToolUse
kubectl describe node NAMEConditions, allocatable vs allocated, taints, events
kubectl top nodeLive CPU and memory (metrics-server)
kubectl debug node/NAME -it --profile=sysadmin --image=busybox:1.37Shell with node root at /host; chroot /host journalctl -u kubelet (needs the privileged sysadmin profile)
crictl ps -a, crictl logs, crictl inspect (on the node)Runtime view, including containers the API does not show
node-problem-detectorTurns kernel and runtime problems into node conditions and events
kube_node_status_conditionAlert NodeNotReady and NodePressure (snippet)

Fix / how to use it: set requests on every Pod so the scheduler cannot overpack nodes, keep log rotation and image garbage collection at defaults or tighter, alert on node conditions, and for NotReady start with kubectl describe node and the kubelet's journal through debug node. The eviction ordering by QoS and priority is in Resources, Scheduling & Autoscaling.

DNS debugging: CoreDNS and ndots Important ​

In plain words: Pods resolve names through CoreDNS using a search list (shop.svc.cluster.local svc.cluster.local cluster.local) and options ndots:5, so a name with fewer than five dots is tried with every search suffix before it is tried as written.

Common misunderstanding: "DNS is slow, CoreDNS needs more replicas." Often each external lookup (api.stripe.com, two dots) becomes four or more queries because of the search list (three cluster suffixes, then the name itself), times two for A and AAAA records. The fix is usually a trailing dot or a lower ndots for that Pod, not more CoreDNS.

Definition: a Pod's /etc/resolv.conf in the default ClusterFirst policy looks like search <namespace>.svc.cluster.local svc.cluster.local cluster.local and options ndots:5. The resolv.conf man page: ndots:n "Sets a threshold for the number of dots which must appear in a name ... before an initial absolute query will be made." CoreDNS runs in kube-system with the label k8s-app=kube-dns and a Service named kube-dns ("for backward compatibility with the original kube-dns"). Its log plugin logs queries ({remote}:{port} - {>id} "{type} {class} {name} {proto} {size} {>do} {>bufsize}" {rcode} {>rflags} {rsize} {duration}), with classes success, denial (NXDOMAIN or nodata), error, all; its errors plugin "enables error logging".

text
Sequence: resolving api.stripe.com from a Pod in namespace shop (ndots:5)
1  api.stripe.com.shop.svc.cluster.local   -> NXDOMAIN
2  api.stripe.com.svc.cluster.local        -> NXDOMAIN
3  api.stripe.com.cluster.local            -> NXDOMAIN
4  api.stripe.com                          -> NOERROR (answer)
   (each step for A and AAAA; a trailing dot "api.stripe.com." goes straight to step 4)

Real scenarios: intermittent 5 s delays from dropped UDP packets on the conntrack table; a Service name that resolves from one namespace but not another (missing .namespace suffix); CoreDNS CrashLoopBackOff because its upstream loop detection saw itself in /etc/resolv.conf on the node; a NetworkPolicy that blocks egress to kube-system on UDP/TCP 53.

Fix / how to use it: the DNS debugging task's order: create a test Pod (dnsutils or netshoot), nslookup kubernetes.default, read /etc/resolv.conf, check the CoreDNS Pods (-l k8s-app=kube-dns), their logs, the kube-dns Service and its EndpointSlices. For external names in hot paths use fully qualified names with a trailing dot or set dnsConfig.options: [{name: ndots, value: "2"}] on that Pod. CoreDNS and kube-proxy internals are in Kubernetes Networking; resolver behaviour is in DNS Resolution for Developers.

Service without endpoints, selector mismatch, NetworkPolicy drop Must-know ​

In plain words: A Service is a name and a virtual IP in front of whatever Pods its selector matches and that are ready. If nothing matches, or the ports do not line up, or a NetworkPolicy drops the packets, clients see errors although every Pod is Running.

Common misunderstanding: "The Service exists, so it routes." A Service with a selector that matches no ready Pod is valid and silent: DNS resolves, the ClusterIP accepts connections nowhere, and clients see "connection refused" or a 503 from the Ingress.

Definition: "Inside the Kubernetes system is a control loop which evaluates the selector of every Service and saves the results into one or more EndpointSlice objects." kubectl get endpointslices -l kubernetes.io/service-name=NAME with an ENDPOINTS column of <none> means "check that the spec.selector field of your Service actually selects for metadata.labels values on your Pods"; the classic mistake is a typo or a different label key (app=hostnames vs run=hostnames). Also check that "the pod's containerPort matches the Service's targetPort". A NetworkPolicy that selects a Pod makes it deny everything not explicitly allowed for the listed policyTypes; dropped packets show up as timeouts, not refusals. NetworkPolicy ports[].port "can either be a numerical or named port on a pod".

text
Sequence: a Helm refactor renames a label
1  chart v2 Pod labels: app.kubernetes.io/name=orders-api   (was app=orders-api)
2  Service selector still app=orders-api
3  kubectl get endpointslices -l kubernetes.io/service-name=orders-api -> ENDPOINTS <none>
4  Ingress: 503; Prometheus: target down for the ServiceMonitor (same selector problem)
5  fix the Service selector; endpoints appear within seconds

Real scenarios: targetPort: 8080 while the container listens on 9090; a named targetPort: http while the container port is named web; readiness failing on all Pods (endpoints exist but are not ready); a default-deny policy in the namespace that also blocks Prometheus scrapes and DNS egress; a ServiceMonitor that selects the Service but names a port the Service does not have.

CheckCommandHealthy result
Service exists, portskubectl get svc NAME -o wideSelector and ports as expected
Endpointskubectl get endpointslices -l kubernetes.io/service-name=NAMEPod IPs listed, ready
Selector matcheskubectl get pods -l KEY=VALUEThe Pods you expect
Pod answers directlynetshoot: curl PODIP:TARGETPORT200
DNSnetshoot: dig NAME.NS.svc.cluster.localThe ClusterIP
Policykubectl get networkpolicy -n NS -o yamlAn ingress rule allowing the client
kube-proxykubectl get pods -n kube-system -l k8s-app=kube-proxyRunning on the node

Fix / how to use it: use one label set (app.kubernetes.io/name) everywhere, name ports and refer to them by name in Services, probes and ServiceMonitors, and add explicit allow rules for monitoring when a namespace has default-deny:

yaml
# With a default-deny ingress policy in "shop", Prometheus (namespace
# "monitoring") can no longer reach :9090 and the target goes DOWN with a
# timeout. This policy allows exactly the scrape.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-prometheus-scrape
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/name: orders-api
  policyTypes: [Ingress]
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: monitoring
          podSelector:
            matchLabels:
              app.kubernetes.io/name: prometheus
      ports:
        - port: metrics
          protocol: TCP

PVC Pending Important ​

In plain words: A PersistentVolumeClaim stays Pending until a volume is bound to it. Sometimes that is by design (it waits for the first Pod), sometimes nothing can ever provision it.

Common misunderstanding: "PVC Pending is always a storage failure." With volumeBindingMode: WaitForFirstConsumer the claim is expected to stay Pending until a Pod that uses it is scheduled; this mode "will delay the binding and provisioning of a PersistentVolume until a Pod using the PersistentVolumeClaim is created". The failure is a PVC that stays Pending after its Pod was scheduled, or with Immediate binding.

Definition: binding needs a matching PersistentVolume or a StorageClass whose provisioner (a CSI driver) creates one. Events on the PVC say which: WaitForFirstConsumer, ProvisioningFailed with the driver's error, no persistent volumes available for this claim and no storage class is set. A claim that names no StorageClass gets the default one if the admission plugin is on and one is marked default; storageClassName: "" explicitly asks for no class.

text
Sequence: a StatefulSet in a new cluster
1  volumeClaimTemplates: storageClassName: fast-ssd
2  kubectl get pvc data-db-0 -> Pending; Events: storageclass.storage.k8s.io "fast-ssd" not found
3  Pod db-0 -> Pending: pod has unbound immediate PersistentVolumeClaims
4  create the StorageClass (or use the default); provisioner creates the PV; PVC Bound; Pod scheduled

Real scenarios: a StorageClass name copied from another cloud; the CSI driver's controller Pod crashing (look at its logs in kube-system); a zonal disk requested in a zone with no capacity; ReadWriteMany requested from a block-storage class that supports only ReadWriteOnce.

Fix / how to use it: kubectl describe pvc first, then the CSI controller's logs, and alert on kube_persistentvolumeclaim_status_phase{phase="Pending"} for 10 minutes (snippet). Access modes, reclaim policies and CSI architecture are owned by Kubernetes Config, Secrets & Storage.

Control plane health: API server health endpoints livez readyz, etcd health, audit Important ​

In plain words: The API server reports its own health on /livez (should I be restarted?) and /readyz (can I take traffic?), each with a list of named checks including etcd. etcd has its own health command. Managed clusters hide most of this behind the provider.

Common misunderstanding: "/healthz is the health check." It "is deprecated (since Kubernetes v1.16), and you should use the more specific livez and readyz endpoints instead". Machines should rely on the HTTP status code; the ?verbose output is "intended to be used by human operators".

Definition: kubectl get --raw='/readyz?verbose' prints one line per check ([+]ping ok, [+]etcd ok, [+]poststarthook/... ok) and healthz check passed; individual checks can be excluded (/readyz?verbose&exclude=etcd). --livez-grace-period covers startup, --shutdown-delay-duration lets /readyz fail before shutdown. etcd: etcdctl endpoint health (with --endpoints, --cacert, --cert, --key on kubeadm clusters, paths under /etc/kubernetes/pki/etcd/). API audit logging (owned by Kubernetes Security) records who did what at levels None, Metadata, Request, RequestResponse and stages such as RequestReceived, ResponseStarted, ResponseComplete, Panic; it is the answer to "who deleted that Deployment?".

text
Sequence: kubectl is slow for everyone
1  kubectl get --raw='/readyz?verbose'        -> [-]etcd failed: reason withheld
2  on a control-plane node: etcdctl endpoint health --cluster
     -> one member reports unhealthy (the other two healthy)
3  node-exporter: disk fsync latency high on that node (etcd is disk-latency sensitive)
4  fix storage; readyz back to all [+]

Real scenarios: an Ingress for the API server checking /healthz and taking it out during a rolling upgrade; etcd running out of space after millions of Events (one reason for the event TTL); a CRD-heavy cluster where kubectl is slow because of discovery, not the server; "who scaled prod to zero?" answered from the audit log.

Fix / how to use it: monitor the API server with kube-prometheus-stack's built-in ServiceMonitors (the chart includes ServiceMonitors for "kubelet, kube-apiserver, kube-controller-manager, kube-scheduler, kube-etcd, kube-proxy, coredns"), use /livez and /readyz in load balancers, and on managed clusters use the provider's control-plane metrics and audit log export.

kubectl plugins: krew, stern, k9s, kubectl-neat Good to know ​

In plain words: kubectl can be extended with any executable named kubectl-something on your PATH; krew installs and updates them. A few save real time during incidents.

Common misunderstanding: "Plugins are needed to debug Kubernetes." Every step of the method works with plain kubectl; plugins make multi-Pod logs, navigation and reading manifests faster. In a locked-down jump host, plain kubectl is what you will have.

Definition: "A plugin is a standalone executable file, whose name begins with kubectl-. To install a plugin, move its executable file to anywhere on your PATH." "Krew is the package manager for kubectl plugins" with over 200 plugins.

ToolInstallWhat it doesNote
sternkubectl krew install sternTails many Pods and containers, colour per Pod, follows new Pods, --since (default 48h), -o jsonFork of the discontinued wercker/stern
k9sPackage managers"a terminal UI to interact with your Kubernetes clusters": navigate, logs, describe, port-forwardNot a krew plugin; a separate binary
kubectl-neatkubectl krew install neat"Remove clutter from Kubernetes manifests": strips status, managed fields, defaultsREADME: "This project is unmaintained"
ktopkubectl krew install ktop, then kubectl ktoptop-like live view of nodes, pods and containers with drill-down to logs; works without metrics infrastructure by showing requests and limitsRuns locally from the kubeconfig
kubectl-netshootkrew (community)Wraps netshoot debug commandsOptional
kubectl plugin listbuilt inLists plugins found on PATH—

Fix / how to use it: install stern and k9s on on-call laptops, pin versions, and keep the runbook in plain kubectl so it works anywhere.

Runbooks and on-call Important ​

In plain words: A runbook is the page an alert links to: what this alert means, how to confirm it, how to stop the bleeding, and who to call. On-call is the rota of people who follow it.

Common misunderstanding: "A runbook is a wiki page of everything we know." The useful ones are short, start from the alert, and give read-only confirmation commands before any action. They are tested like code: someone who has never seen the service follows them in a game day.

Definition: in this chapter every alert carries a runbook_url annotation; the runbook section for each has the same headings: Meaning, Impact, Confirm (the commands of the method), Mitigate (rollback, scale, failover), Fix later, Escalate. Alert design, paging thresholds and SLO burn rates are owned by Alerting That Actually Works.

text
Runbook: OrdersAPIHighErrorRate (excerpt)
Meaning   5xx ratio of a route > 5 % for 5 minutes
Confirm   1 Grafana RED row for orders-api: one route or all?
          2 k8s-triage.sh deploy shop orders-api   (new ReplicaSet? restarts? Warning events?)
          3 Loki: {namespace="shop", app="orders-api"} | json | level="ERROR"
Mitigate  kubectl rollout undo deploy/orders-api -n shop   (if a deploy started it)
Escalate  #orders-oncall after 15 minutes without mitigation

Real scenarios: an alert that fired 40 times a week and was muted (deleted after the runbook review found no action); a runbook whose first step was kubectl delete pod (rewritten to collect --previous logs first); an on-call engineer without RBAC for ephemeral containers at 03:00 (fixed with the debugger role).

Fix / how to use it: link every alert to a runbook, start every runbook with the read-only triage script, export Events and logs so the runbook works after an hour, and review runbooks after each incident.

Mechanics ​

How kubectl logs, exec, port-forward and debug reach a container ​

None of these commands talk to the node directly. kubectl calls the API server; the API server proxies the request to the kubelet on the Pod's node (port 10250, authenticated with the API server's client certificate); the kubelet reads the log file or asks the container runtime over CRI to exec, attach or forward. That is why a node whose kubelet is down cannot serve kubectl logs even though the files are on its disk, why kubectl logs --insecure-skip-tls-verify-backend exists ("if your kubelet serving certificates have expired"), and why RBAC on the subresources pods/log, pods/exec, pods/portforward and pods/ephemeralcontainers is what controls access.

text
kubectl logs -f orders-api-7d9c
1  kubectl  -> GET /api/v1/namespaces/shop/pods/orders-api-7d9c/log?follow=true    (API server, RBAC pods/log)
2  API server -> kubelet API on the Pod's node (port 10250)
3  kubelet reads the newest log file under /var/log/pods for that container
4  stream flows back the same way; the kubelet-to-API-server hop is why a NotReady node has no logs

How an Event is born, merged and expires ​

A component calls its event recorder with the object, type, reason and message. The client library aggregates identical events: instead of a new object it updates the existing one (series.count and lastObservedTime in events.k8s.io/v1, count and lastTimestamp in core v1). The API server stores Events in etcd with a lease of --event-ttl (default one hour), after which etcd deletes them. Events are therefore cheap for the reader but a real load on etcd in large clusters, which is why the TTL is short and why exporting them is the platform's job.

Label cardinality: why route, not path ​

Every distinct combination of label values is a separate time series in Prometheus (and a separate stream in Loki). http_requests_total{route, method, code} for 20 routes, 4 methods and 6 codes is at most 480 series per Pod; the same counter labelled with the raw path /orders/42 grows by one series per order. The Go before package in this chapter proves it: 100 order ids give 100 series; the observe package gives one. Prometheus's naming guide says "Do not use labels to store dimensions with high cardinality (many different label values), such as user IDs, email addresses, or other unbounded sets of values", and Loki's: "never use a label which can have unbounded or infinite values". Pod names are bounded per moment but churn on every deploy, which is why the Fluent Bit snippet puts pod and correlation_id into Loki structured metadata, which "works well for high cardinality data that isn't suited for using labels".

Knobs ​

KnobWhereDefaultEffect
--event-ttlkube-apiserver1h0m0sHow long Events live
containerLogMaxSize / containerLogMaxFilesKubeletConfiguration10Mi / 5Rotation per container; kubectl logs reads the newest file only
containerLogMaxWorkers / containerLogMonitorIntervalKubeletConfiguration— / 10sConcurrency and frequency of rotation
podLogsDirKubeletConfiguration/var/log/podsChanging it is "at your own risk"
evictionHardKubeletConfigurationmemory.available<100Mi, nodefs.available<10%, imagefs.available<15%, nodefs.inodesFree<5%When the kubelet evicts
--node-monitor-grace-periodkube-controller-manager50sTime before a silent node is marked unhealthy
terminationMessagePolicyContainerFileFallbackToLogsOnError uses the log tail when the file is empty
--max-log-requestskubectl logs5Concurrent streams with -l
--tailkubectl logs-1, or 10 with a selectorLines returned
--profilekubectl debuggeneral (v1.36 client)Security context of the debug container
interval / scrapeTimeoutServiceMonitor endpointPrometheus globalScrape frequency and timeout
serviceMonitorSelectorNilUsesHelmValueskube-prometheus-stacktrueOnly objects with release: RELEASE are selected
prometheus.prometheusSpec.retentionkube-prometheus-stack10dMetrics history
mode / replicaCountOpenTelemetry Collector chartmust be set / 1DaemonSet vs Deployment collector
Mem_Buf_LimitFluent Bit tail input (chart default)5MBBack-pressure before the agent drops or pauses

Error messages you will actually see ​

Message (source)MeaningSection
0/3 nodes are available: 3 Insufficient cpu. (scheduler)No node has enough free requestsPending
node(s) had untolerated taint(s) / node(s) didn't match Pod's node affinity/selector (scheduler)Placement rules exclude every nodePending
pod has unbound immediate PersistentVolumeClaims (scheduler)Volume not boundPVC Pending
Back-off restarting failed container (kubelet, reason BackOff)CrashLoopBackOff waitingCrashLoopBackOff
Error: couldn't find key pasword in Secret shop/shop-db (kubelet, reason Failed)CreateContainerConfigErrorCannot start
Readiness probe failed: HTTP probe failed with statuscode: 503 (kubelet, reason Unhealthy)Not Ready, out of endpointsNot Ready
Kubelet stopped posting node status. (node controller, NodeStatusUnknown)Node lostNode problems
OCI runtime exec failed: ... executable file not found in $PATH (kubectl exec)No shell in the imageGetting a shell
cannot patch resource "pods/ephemeralcontainers" (API server, Forbidden)RBAC lacks ephemeral containersGetting a shell
nslookup: can't resolve 'kubernetes.default' (inside a Pod)CoreDNS or its Service brokenDNS
[-]etcd failed: reason withheld (/readyz)API server cannot reach etcdControl plane
The connection to the server localhost:8080 was refused (kubectl)No kubeconfig or wrong context, not a cluster outageLab

Go ​

The Go service from the platform chapters, made observable: one JSON line per log event on stdout with correlation_id and trace_id, RED metrics with a bounded route label, /metrics and probes on a separate admin port that the Service exposes as metrics and no Ingress routes to.

Before ​

Labels by raw path and logs plain text through the global registry. It compiles and works; it just cannot be operated at scale. The test proves the cardinality problem.

go
// Package before shows the instrumentation that looks fine on a laptop and
// hurts in a cluster: plain-text logs and a metric labelled with the raw URL
// path. Every distinct order ID becomes a new time series in Prometheus.
package before

import (
	"log"
	"net/http"
	"strconv"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
)

// Requests is registered on the global default registry by promauto, so
// every test and every package that imports this one shares (and pollutes) it.
var Requests = promauto.NewCounterVec(
	prometheus.CounterOpts{
		Name: "orders_requests_total",
		Help: "Requests by raw path and status.",
	},
	[]string{"path", "status"}, // "path" is unbounded: /orders/1, /orders/2, ...
)

// Handler serves /orders/{id} and counts each request by its raw path.
func Handler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		status := http.StatusOK
		if r.PathValue("id") == "" {
			status = http.StatusNotFound
		}
		w.WriteHeader(status)
		// Unstructured text: no level, no correlation id, nothing a log
		// pipeline can filter on without a regular expression.
		log.Printf("served %s %s -> %d", r.Method, r.URL.Path, status)
		Requests.WithLabelValues(r.URL.Path, strconv.Itoa(status)).Inc()
	})
}
go
package before

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/prometheus/client_golang/prometheus/testutil"
)

// TestRawPathLabelExplodesCardinality proves the problem: 100 different order
// IDs produce 100 different series for one logical endpoint.
func TestRawPathLabelExplodesCardinality(t *testing.T) {
	log.SetOutput(io.Discard)
	Requests.Reset()
	mux := http.NewServeMux()
	mux.Handle("GET /orders/{id}", Handler())
	for i := 1; i <= 100; i++ {
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, fmt.Sprintf("/orders/%d", i), nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status %d", rec.Code)
		}
	}
	if got := testutil.CollectAndCount(Requests); got != 100 {
		t.Fatalf("series = %d, want 100 (one per order id)", got)
	}
}

After ​

observe holds the metrics and the logging middleware; service wires them into two listeners and shuts down by turning readiness off first.

go
// Package observe holds the RED metrics and the structured, correlated
// logging that a Go service needs before it is worth deploying to Kubernetes.
package observe

import (
	"net/http"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/collectors"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Metrics are the RED signals (Rate, Errors, Duration) for every route.
// The "route" label is the ServeMux pattern, never the raw path, so the
// number of series is bounded by the number of routes.
type Metrics struct {
	Requests *prometheus.CounterVec
	Duration *prometheus.HistogramVec
	InFlight prometheus.Gauge
}

// NewRegistry returns a private registry with the Go runtime and process
// collectors. A private registry keeps tests independent and avoids
// exporting whatever some imported library registered globally.
func NewRegistry() *prometheus.Registry {
	reg := prometheus.NewRegistry()
	reg.MustRegister(
		collectors.NewGoCollector(),
		collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
	)
	return reg
}

// NewMetrics creates and registers the RED metrics on reg.
func NewMetrics(reg prometheus.Registerer) *Metrics {
	m := &Metrics{
		Requests: prometheus.NewCounterVec(prometheus.CounterOpts{
			Name: "http_requests_total",
			Help: "HTTP requests by route pattern, method and status code.",
		}, []string{"route", "method", "code"}),
		Duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
			Name:    "http_request_duration_seconds",
			Help:    "HTTP request latency by route pattern, method and status code.",
			Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5},
		}, []string{"route", "method", "code"}),
		InFlight: prometheus.NewGauge(prometheus.GaugeOpts{
			Name: "http_requests_in_flight",
			Help: "HTTP requests currently being served.",
		}),
	}
	reg.MustRegister(m.Requests, m.Duration, m.InFlight)
	return m
}

// Instrument wraps h for one route pattern. promhttp fills "method" and
// "code"; the route is curried in, so the remaining labels are exactly the
// two that promhttp accepts.
func (m *Metrics) Instrument(route string, h http.Handler) http.Handler {
	labels := prometheus.Labels{"route": route}
	return promhttp.InstrumentHandlerInFlight(m.InFlight,
		promhttp.InstrumentHandlerDuration(m.Duration.MustCurryWith(labels),
			promhttp.InstrumentHandlerCounter(m.Requests.MustCurryWith(labels), h),
		),
	)
}

// Handler serves the registry in the Prometheus text format, or OpenMetrics
// when the scraper asks for it. Registry: reg also counts scrape errors.
func Handler(reg *prometheus.Registry) http.Handler {
	return promhttp.HandlerFor(reg, promhttp.HandlerOpts{
		Registry:          reg,
		EnableOpenMetrics: true,
	})
}
go
package observe

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"io"
	"log/slog"
	"net/http"
	"strings"
	"time"
)

// HeaderRequestID is the correlation header accepted from callers and
// echoed on every response.
const HeaderRequestID = "X-Request-ID"

type loggerKey struct{}

// NewLogger writes one JSON object per line to w (stdout in a container),
// which is what the kubelet, Fluent Bit, Vector and the OpenTelemetry
// Collector filelog receiver all expect.
func NewLogger(w io.Writer, level slog.Leveler) *slog.Logger {
	return slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level}))
}

// Logger returns the request-scoped logger stored by Correlate, or the
// process default when called outside a request.
func Logger(ctx context.Context) *slog.Logger {
	if l, ok := ctx.Value(loggerKey{}).(*slog.Logger); ok {
		return l
	}
	return slog.Default()
}

// Correlate gives every request a correlation id (taken from X-Request-ID
// when it is safe, generated otherwise), echoes it on the response, adds the
// W3C trace id when a traceparent header is present, and writes one access
// log line per request.
func Correlate(base *slog.Logger, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := r.Header.Get(HeaderRequestID)
		if !validID(id) {
			id = newID()
		}
		w.Header().Set(HeaderRequestID, id)

		l := base.With("correlation_id", id)
		if tid, ok := traceID(r.Header.Get("traceparent")); ok {
			l = l.With("trace_id", tid)
		}

		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		start := time.Now()
		next.ServeHTTP(rec, r.WithContext(context.WithValue(r.Context(), loggerKey{}, l)))

		level := slog.LevelInfo
		if rec.status >= 500 {
			level = slog.LevelError
		}
		l.Log(r.Context(), level, "request",
			"method", r.Method,
			"path", r.URL.Path,
			"status", rec.status,
			"duration_ms", time.Since(start).Milliseconds(),
		)
	})
}

// validID accepts 1-64 characters from a conservative set, so a caller
// cannot inject newlines or huge values into every log line.
func validID(s string) bool {
	if len(s) == 0 || len(s) > 64 {
		return false
	}
	for _, c := range s {
		switch {
		case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '-', c == '_', c == '.':
		default:
			return false
		}
	}
	return true
}

func newID() string {
	b := make([]byte, 16)
	_, _ = rand.Read(b) // crypto/rand.Read never returns an error since Go 1.24
	return hex.EncodeToString(b)
}

// traceID extracts the trace-id field of a W3C traceparent header
// ("00-<32 hex>-<16 hex>-<2 hex>").
func traceID(tp string) (string, bool) {
	parts := strings.Split(tp, "-")
	if len(parts) != 4 || len(parts[1]) != 32 || parts[1] == strings.Repeat("0", 32) {
		return "", false
	}
	if _, err := hex.DecodeString(parts[1]); err != nil {
		return "", false
	}
	return parts[1], true
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) {
	s.status = code
	s.ResponseWriter.WriteHeader(code)
}
go
package observe

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/prometheus/client_golang/prometheus/testutil"
)

func TestRouteLabelIsBounded(t *testing.T) {
	reg := NewRegistry()
	m := NewMetrics(reg)
	mux := http.NewServeMux()
	mux.Handle("GET /orders/{id}", m.Instrument("/orders/{id}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})))
	for i := 1; i <= 100; i++ {
		mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, fmt.Sprintf("/orders/%d", i), nil))
	}
	if got := testutil.CollectAndCount(m.Requests); got != 1 {
		t.Fatalf("series = %d, want 1 for one route", got)
	}
	want := `
# HELP http_requests_total HTTP requests by route pattern, method and status code.
# TYPE http_requests_total counter
http_requests_total{code="200",method="get",route="/orders/{id}"} 100
`
	if err := testutil.CollectAndCompare(m.Requests, strings.NewReader(want)); err != nil {
		t.Fatal(err)
	}
}

func TestCorrelateKeepsSafeIDAndLogsJSON(t *testing.T) {
	var buf bytes.Buffer
	h := Correlate(NewLogger(&buf, slog.LevelInfo), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		Logger(r.Context()).Info("loading order", "order_id", "42")
		w.WriteHeader(http.StatusTeapot)
	}))
	req := httptest.NewRequest(http.MethodGet, "/orders/42", nil)
	req.Header.Set(HeaderRequestID, "abc-123")
	req.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)

	if got := rec.Header().Get(HeaderRequestID); got != "abc-123" {
		t.Fatalf("echoed id = %q", got)
	}
	lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
	if len(lines) != 2 {
		t.Fatalf("want 2 log lines (handler + access), got %d: %s", len(lines), buf.String())
	}
	for _, line := range lines {
		var rec map[string]any
		if err := json.Unmarshal([]byte(line), &rec); err != nil {
			t.Fatalf("not JSON: %s", line)
		}
		if rec["correlation_id"] != "abc-123" || rec["trace_id"] != "4bf92f3577b34da6a3ce929d0e0e4736" {
			t.Fatalf("missing correlation fields: %s", line)
		}
	}
	var access map[string]any
	_ = json.Unmarshal([]byte(lines[1]), &access)
	if access["msg"] != "request" || access["status"] != float64(http.StatusTeapot) {
		t.Fatalf("access line = %s", lines[1])
	}
}

func TestCorrelateReplacesUnsafeID(t *testing.T) {
	var buf bytes.Buffer
	h := Correlate(NewLogger(&buf, slog.LevelInfo), http.NotFoundHandler())
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	req.Header.Set(HeaderRequestID, "evil\ninjected")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	got := rec.Header().Get(HeaderRequestID)
	if len(got) != 32 || strings.Contains(buf.String(), "injected") {
		t.Fatalf("unsafe id not replaced: header=%q log=%s", got, buf.String())
	}
}

func TestServerErrorsLogAtErrorLevel(t *testing.T) {
	var buf bytes.Buffer
	h := Correlate(NewLogger(&buf, slog.LevelInfo), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusInternalServerError)
	}))
	h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
	if !strings.Contains(buf.String(), `"level":"ERROR"`) {
		t.Fatalf("5xx not logged at ERROR: %s", buf.String())
	}
}
go
// Command service is the orders API from the platform chapters, now with what
// a cluster operator needs: JSON logs on stdout with a correlation id, RED
// metrics on a separate metrics port for a ServiceMonitor, and probes.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"net"
	"net/http"
	"os"
	"os/signal"
	"sync/atomic"
	"syscall"
	"time"

	"academy/kubernetes-observability-troubleshooting/observe"
	"github.com/prometheus/client_golang/prometheus"
)

func main() {
	logger := observe.NewLogger(os.Stdout, slog.LevelInfo)
	slog.SetDefault(logger)
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
	defer stop()

	drain, err := time.ParseDuration(env("SHUTDOWN_DELAY", "5s"))
	if err != nil {
		logger.Error("exit", "err", err)
		os.Exit(1)
	}
	appLn, err := net.Listen("tcp", env("APP_ADDR", ":8080"))
	if err != nil {
		logger.Error("exit", "err", err)
		os.Exit(1)
	}
	adminLn, err := net.Listen("tcp", env("METRICS_ADDR", ":9090"))
	if err != nil {
		logger.Error("exit", "err", err)
		os.Exit(1)
	}
	if err := run(ctx, appLn, adminLn, logger, drain); err != nil {
		logger.Error("exit", "err", err)
		os.Exit(1)
	}
}

func env(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}

// appHandler serves business routes; only these are instrumented with RED
// metrics, so probes and scrapes do not pollute the request rate.
func appHandler(m *observe.Metrics, logger *slog.Logger) http.Handler {
	mux := http.NewServeMux()
	mux.Handle("GET /orders/{id}", m.Instrument("/orders/{id}", http.HandlerFunc(getOrder)))
	return observe.Correlate(logger, mux)
}

// adminHandler serves /metrics and the probes on the metrics port, which the
// Service exposes as the "metrics" port and no Ingress routes to.
func adminHandler(reg *prometheus.Registry, ready *atomic.Bool) http.Handler {
	mux := http.NewServeMux()
	mux.Handle("GET /metrics", observe.Handler(reg))
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
		if !ready.Load() {
			http.Error(w, "not ready", http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK)
	})
	return mux
}

func getOrder(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	log := observe.Logger(r.Context()).With("order_id", id)
	switch id {
	case "0":
		log.Warn("order not found")
		http.Error(w, "not found", http.StatusNotFound)
		return
	case "fail":
		log.Error("order store unavailable")
		http.Error(w, "upstream error", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(map[string]string{"id": id, "status": "paid"})
}

// run serves both listeners until ctx is cancelled. Then it turns readiness
// off, keeps serving for drain so the readiness probe fails and the Pod
// leaves the EndpointSlices, and only then shuts down with an 8 s budget.
// drain + 8 s must stay below terminationGracePeriodSeconds (30 s default).
func run(ctx context.Context, appLn, adminLn net.Listener, logger *slog.Logger, drain time.Duration) error {
	reg := observe.NewRegistry()
	m := observe.NewMetrics(reg)
	var ready atomic.Bool

	app := &http.Server{Handler: appHandler(m, logger), ReadHeaderTimeout: 5 * time.Second}
	admin := &http.Server{Handler: adminHandler(reg, &ready), ReadHeaderTimeout: 5 * time.Second}

	errc := make(chan error, 2)
	serve := func(s *http.Server, ln net.Listener) {
		logger.Info("listening", "addr", ln.Addr().String())
		if err := s.Serve(ln); !errors.Is(err, http.ErrServerClosed) {
			errc <- err
		}
	}
	go serve(app, appLn)
	go serve(admin, adminLn)
	ready.Store(true)

	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
	}
	ready.Store(false)
	logger.Info("draining", "delay", drain.String())
	time.Sleep(drain)
	logger.Info("shutting down")
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
	defer cancel()
	return errors.Join(app.Shutdown(shutdownCtx), admin.Shutdown(shutdownCtx))
}
go
package main

import (
	"bytes"
	"context"
	"io"
	"log/slog"
	"net"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"academy/kubernetes-observability-troubleshooting/observe"
)

func TestMetricsEndpointShowsREDSeries(t *testing.T) {
	var logs bytes.Buffer
	reg := observe.NewRegistry()
	m := observe.NewMetrics(reg)
	var ready atomic.Bool
	app := httptest.NewServer(appHandler(m, observe.NewLogger(&logs, slog.LevelInfo)))
	defer app.Close()
	admin := httptest.NewServer(adminHandler(reg, &ready))
	defer admin.Close()

	for _, p := range []string{"/orders/42", "/orders/43", "/orders/fail", "/orders/0"} {
		resp, err := http.Get(app.URL + p)
		if err != nil {
			t.Fatal(err)
		}
		resp.Body.Close()
	}

	resp, err := http.Get(admin.URL + "/metrics")
	if err != nil {
		t.Fatal(err)
	}
	body, _ := io.ReadAll(resp.Body)
	resp.Body.Close()
	for _, want := range []string{
		`http_requests_total{code="200",method="get",route="/orders/{id}"} 2`,
		`http_requests_total{code="500",method="get",route="/orders/{id}"} 1`,
		`http_requests_total{code="404",method="get",route="/orders/{id}"} 1`,
		`http_request_duration_seconds_bucket{code="200",method="get",route="/orders/{id}",le="+Inf"} 2`,
		`go_goroutines`,
	} {
		if !strings.Contains(string(body), want) {
			t.Errorf("metrics output lacks %q", want)
		}
	}
	if !strings.Contains(logs.String(), `"msg":"order store unavailable"`) {
		t.Errorf("error log missing: %s", logs.String())
	}
}

func TestReadinessFollowsFlag(t *testing.T) {
	var ready atomic.Bool
	h := adminHandler(observe.NewRegistry(), &ready)
	check := func() int {
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil))
		return rec.Code
	}
	if c := check(); c != http.StatusServiceUnavailable {
		t.Fatalf("before start: %d", c)
	}
	ready.Store(true)
	if c := check(); c != http.StatusOK {
		t.Fatalf("after start: %d", c)
	}
}

// TestRunDrainsBeforeShutdown proves the shutdown order: after cancel the
// admin port still answers, but /readyz is 503, so the kubelet marks the Pod
// not ready while in-flight and late requests are still served.
func TestRunDrainsBeforeShutdown(t *testing.T) {
	appLn, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	adminLn, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan error, 1)
	go func() {
		done <- run(ctx, appLn, adminLn, observe.NewLogger(io.Discard, slog.LevelInfo), 300*time.Millisecond)
	}()

	readyz := "http://" + adminLn.Addr().String() + "/readyz"
	status := func() int {
		resp, err := http.Get(readyz)
		if err != nil {
			return 0
		}
		resp.Body.Close()
		return resp.StatusCode
	}
	deadline := time.Now().Add(2 * time.Second)
	for status() != http.StatusOK {
		if time.Now().After(deadline) {
			t.Fatal("never became ready")
		}
		time.Sleep(10 * time.Millisecond)
	}

	cancel()
	time.Sleep(50 * time.Millisecond)
	if got := status(); got != http.StatusServiceUnavailable {
		t.Fatalf("during drain /readyz = %d, want 503", got)
	}
	resp, err := http.Get("http://" + appLn.Addr().String() + "/orders/7")
	if err != nil || resp.StatusCode != http.StatusOK {
		t.Fatalf("app must still serve during drain: %v %v", err, resp)
	}
	resp.Body.Close()
	if err := <-done; err != nil {
		t.Fatalf("run returned %v", err)
	}
}
text
module academy/kubernetes-observability-troubleshooting

go 1.24

require github.com/prometheus/client_golang v1.23.2

require (
	github.com/beorn7/perks v1.0.1 // indirect
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/kr/text v0.2.0 // indirect
	github.com/kylelemons/godebug v1.1.0 // indirect
	github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
	github.com/prometheus/client_model v0.6.2 // indirect
	github.com/prometheus/common v0.66.1 // indirect
	github.com/prometheus/procfs v0.16.1 // indirect
	go.yaml.in/yaml/v2 v2.4.2 // indirect
	golang.org/x/sys v0.35.0 // indirect
	google.golang.org/protobuf v1.36.8 // indirect
)

The Go angle ​

  • promhttp /metrics. promhttp.Handler() serves the global prometheus.DefaultGatherer and "is meant to cover the bulk of basic use cases"; for "a non-default Gatherer, different instrumentation, and non-default HandlerOpts, use the HandlerFor function". The service uses HandlerFor(reg, HandlerOpts{Registry: reg, EnableOpenMetrics: true}) with a private registry, so tests are independent and nothing a library registered globally leaks out. With EnableOpenMetrics the handler answers OpenMetrics when Prometheus asks for it (the lab shows # TYPE http_requests counter and # EOF in that format, and the classic _total name in the text format).
  • Middleware instead of hand-written counters. promhttp.InstrumentHandlerCounter and InstrumentHandlerDuration accept vectors with only the labels code and method ("The function panics otherwise"); MustCurryWith(prometheus.Labels{"route": route}) fixes the route per handler. Methods are normalised (GET becomes get, unknown methods unknown), which also bounds cardinality.
  • Go metrics endpoint on its own port. A separate http.Server on METRICS_ADDR keeps /metrics, /healthz and /readyz out of the public Ingress and out of the RED metrics (probes would otherwise dominate request rates).
  • Runtime and process collectors. collectors.NewGoCollector() and collectors.NewProcessCollector() add go_goroutines, GC and memory statistics and process_resident_memory_bytes; drop unused series with metricRelabelings in the ServiceMonitor, as the snippet does for GC histograms.
  • Structured logging stdout. log/slog with slog.NewJSONHandler(os.Stdout, ...) writes one JSON object per line: exactly what the CRI format wraps and what Fluent Bit's Merge_Log and the OpenTelemetry filelog receiver parse. A request-scoped logger in the context (observe.Logger(ctx)) carries correlation_id and trace_id into every line. The incoming X-Request-ID is accepted only if it is short and safe, so callers cannot inject newlines into logs.
  • Version pins. github.com/prometheus/client_golang v1.23.2 is the newest release whose go.mod declares go 1.23.0; v1.24.0 requires Go 1.25 and v1.25.0 Go 1.26, so they cannot be used in a module that declares go 1.24. Go 1.22 added method and wildcard patterns to net/http.ServeMux (GET /orders/{id}), which give the bounded route label for free; Go 1.24 made crypto/rand.Read "guaranteed not to fail".
  • Shutdown and readiness. On SIGTERM the service sets readiness false, keeps serving for SHUTDOWN_DELAY (default 5 s) so that kube-proxy and Ingress controllers, which learn about a terminating Pod with some delay, can stop routing to it before the listeners close, then calls Shutdown with an 8 s budget; 5 s + 8 s stays inside the Pod's 30 s grace period (TestRunDrainsBeforeShutdown checks the order: /readyz 503 while the app port still answers). Lifecycle details are in Kubernetes Workloads.
  • Tracing. The middleware only reads traceparent; full tracing uses the OpenTelemetry Go SDK and otelhttp, exporting OTLP to the node's collector agent (OTEL_EXPORTER_OTLP_ENDPOINT=http://$(NODE_IP):4318), which is out of scope here and covered in Observability: Logs, Metrics, Traces.

Laravel ​

Before ​

php
<?php

// config/logging.php in a typical first deployment to Kubernetes
return [
    'default' => env('LOG_CHANNEL', 'stack'),
    'channels' => [
        // storage/logs/laravel.log inside the container's writable layer:
        // invisible to kubectl logs and to the node agent, lost on restart,
        // and it counts against the Pod's ephemeral storage until eviction.
        'stack' => ['driver' => 'stack', 'channels' => ['daily']],
        'daily' => ['driver' => 'daily', 'path' => storage_path('logs/laravel.log'), 'days' => 14],
    ],
];

// And a metrics route that counts in memory:
// Route::get('/metrics', fn () => 'requests_total ' . ++$GLOBALS['n']);
// Every php-fpm worker has its own $GLOBALS and the process ends after the request,
// so the value is always 1.

After ​

Laravel JSON logs on stderr (the skeleton's stderr channel with LOG_STDERR_FORMATTER set to Monolog's JsonFormatter), a correlation id in Laravel's Context so it appears on every log line and in queued jobs, RED metrics in APCu shared by the Pod's php-fpm workers, and the php-fpm exporter as a sidecar.

php
<?php

// config/logging.php (excerpt). In a container the only log destination is
// stdout/stderr: the kubelet captures it, rotates it, and a node agent
// (Fluent Bit, Vector, the OpenTelemetry Collector) ships it.
// Pod env: LOG_CHANNEL=stderr, LOG_STDERR_FORMATTER=Monolog\Formatter\JsonFormatter

use Monolog\Handler\StreamHandler;
use Monolog\Processor\PsrLogMessageProcessor;

return [

    'default' => env('LOG_CHANNEL', 'stack'),

    'channels' => [

        // Same shape as the Laravel 13 skeleton's stderr channel; the
        // formatter comes from the environment, so local runs can keep the
        // human-readable LineFormatter and Pods emit one JSON object per line.
        'stderr' => [
            'driver' => 'monolog',
            'level' => env('LOG_LEVEL', 'info'),
            'handler' => StreamHandler::class,
            'handler_with' => [
                'stream' => 'php://stderr',
            ],
            'formatter' => env('LOG_STDERR_FORMATTER'),
            'processors' => [PsrLogMessageProcessor::class],
        ],

        // Never in a Pod: a file inside the container's writable layer is
        // invisible to kubectl logs and lost when the container restarts.
        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
        ],

        'stack' => [
            'driver' => 'stack',
            'channels' => explode(',', (string) env('LOG_STACK', 'single')),
            'ignore_exceptions' => false,
        ],
    ],

];
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

/**
 * Gives every request a correlation id. Laravel's Context is appended to
 * every log entry written during the request and travels with queued jobs,
 * so the web log line and the queue worker's log line share one id.
 */
class AssignCorrelationId
{
    public function handle(Request $request, Closure $next): Response
    {
        $incoming = (string) $request->header('X-Request-ID', '');
        $id = preg_match('/^[A-Za-z0-9._-]{1,64}$/', $incoming) === 1
            ? $incoming
            : Str::uuid()->toString();

        Context::add('correlation_id', $id);

        // Join logs to traces when an OpenTelemetry-instrumented proxy or
        // client sent a W3C traceparent header.
        $traceparent = (string) $request->header('traceparent', '');
        if (preg_match('/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/', $traceparent, $m) === 1) {
            Context::add('trace_id', $m[1]);
        }

        $response = $next($request);
        $response->headers->set('X-Request-ID', $id);

        return $response;
    }
}
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Prometheus\CollectorRegistry;
use Symfony\Component\HttpFoundation\Response;

/**
 * RED metrics for Laravel. PHP-FPM workers share no memory, so the registry
 * must be backed by APCu (per Pod) or Redis (shared); see AppServiceProvider.
 */
class RecordRequestMetrics
{
    public function __construct(private CollectorRegistry $registry)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        $start = hrtime(true);
        $response = $next($request);

        // The route URI pattern ("orders/{order}"), never the raw path:
        // one series per route, not one per order id.
        $route = $request->route()?->uri() ?? 'unmatched';
        $labels = [$route, $request->method(), (string) $response->getStatusCode()];

        $this->registry
            ->getOrRegisterCounter('shop', 'http_requests_total', 'HTTP requests by route, method and status.', ['route', 'method', 'code'])
            ->inc($labels);

        $this->registry
            ->getOrRegisterHistogram('shop', 'http_request_duration_seconds', 'HTTP request latency.', ['route', 'method', 'code'], [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5])
            ->observe((hrtime(true) - $start) / 1e9, $labels);

        return $response;
    }
}
php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Prometheus\CollectorRegistry;
use Prometheus\Storage\APCng;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // APCng keeps counters in shared memory of this Pod's php-fpm master,
        // so all workers in the Pod add to the same numbers. Prometheus sums
        // across Pods. A php-fpm restart resets them; rate() handles that.
        $this->app->singleton(CollectorRegistry::class, fn () => new CollectorRegistry(new APCng()));
    }
}
php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Prometheus\CollectorRegistry;
use Prometheus\RenderTextFormat;

/**
 * Serves the Prometheus text format for the PodMonitor. Nginx only allows
 * this location from inside the cluster (see the Pod's nginx config).
 */
class MetricsController
{
    public function __invoke(CollectorRegistry $registry): Response
    {
        $renderer = new RenderTextFormat();

        return response($renderer->render($registry->getMetricFamilySamples()), 200, [
            'Content-Type' => RenderTextFormat::MIME_TYPE,
        ]);
    }
}
php
<?php

// Loaded from bootstrap/app.php withRouting(then: ...) without the web
// middleware group: no session, no CSRF, no cookies for scrapes.

use App\Http\Controllers\MetricsController;
use Illuminate\Support\Facades\Route;

Route::get('/metrics', MetricsController::class);
ini
; Enables the php-fpm status page the exporter scrapes over FastCGI.
; The directives are commented out in php-fpm's default www.conf.
[www]
pm.status_path = /status
ping.path = /ping
yaml
# Laravel on php-fpm + nginx in one Pod, plus the php-fpm exporter sidecar.
# Logs: php-fpm writes JSON to stderr (LOG_STDERR_FORMATTER), the kubelet
# stores it per container; `kubectl logs deploy/shop-web -c app` reads it.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-web
  namespace: shop
spec:
  replicas: 3
  selector:
    matchLabels:
      app.kubernetes.io/name: shop-web
  template:
    metadata:
      labels:
        app.kubernetes.io/name: shop-web
    spec:
      containers:
        - name: app
          image: ghcr.io/example/shop-app:2.8.0
          env:
            - name: LOG_CHANNEL
              value: stderr
            - name: LOG_STDERR_FORMATTER
              value: Monolog\Formatter\JsonFormatter
            - name: LOG_LEVEL
              value: info
          ports:
            - name: fastcgi
              containerPort: 9000
          resources:
            requests:
              cpu: 500m
              memory: 256Mi
            limits:
              memory: 512Mi
        - name: nginx
          image: ghcr.io/example/shop-nginx:2.8.0
          ports:
            - name: http
              containerPort: 8080
          readinessProbe:
            httpGet:
              path: /up          # Laravel's health route
              port: http
            periodSeconds: 5
        - name: fpm-exporter
          image: hipages/php-fpm_exporter:2.2.0
          env:
            - name: PHP_FPM_SCRAPE_URI
              value: tcp://127.0.0.1:9000/status   # needs pm.status_path = /status
            - name: PHP_FPM_FIX_PROCESS_COUNT
              value: "true"
          ports:
            - name: fpm-metrics
              containerPort: 9253
          resources:
            requests:
              cpu: 10m
              memory: 16Mi
            limits:
              memory: 32Mi

The Laravel angle ​

  • Laravel JSON logs. Laravel 13's skeleton already defines a stderr channel (monolog driver, StreamHandler on php://stderr, 'formatter' => env('LOG_STDERR_FORMATTER'), PsrLogMessageProcessor). Setting LOG_CHANNEL=stderr and LOG_STDERR_FORMATTER=Monolog\Formatter\JsonFormatter in the Pod is the whole change; the docs say the formatter option takes a Monolog formatter class ("the Monolog LineFormatter will be used as the default formatter"). php-fpm forwards worker output to its own stderr when catch_workers_output is enabled, which the official php-fpm image configures.
  • Correlation id with Context. "Information added to the context is automatically appended as metadata to any log entries that are written throughout the request", and "Information added to the context is also made available to jobs dispatched to the queue": one Context::add('correlation_id', ...) in middleware ties the web request and the queue worker's log lines together. Log::withContext and Log::shareContext are the older per-channel alternatives the logging docs still document.
  • Metrics in a share-nothing runtime. promphp/prometheus_client_php "uses Redis or APCu to do the client side aggregation"; APCng keeps the numbers per Pod (Prometheus sums Pods), Redis shares them across Pods. The route label is $request->route()?->uri() (orders/{order}), never the path.
  • php-fpm exporter. hipages/php-fpm_exporter listens on :9253 and scrapes php-fpm's status page over FastCGI (PHP_FPM_SCRAPE_URI, default tcp://127.0.0.1:9000/status); the status page needs pm.status_path = /status, which is commented out in php-fpm's default pool config. Key series: phpfpm_active_processes, phpfpm_listen_queue (requests waiting for a worker: saturation in USE terms), phpfpm_max_children_reached (pool too small), phpfpm_slow_requests.
  • Health route. Laravel's health route "is served at /up and will return a 200 HTTP response if the application has booted without exceptions. Otherwise, a 500 HTTP response will be returned"; it is the readiness target behind Nginx, and anything heavier (database checks) belongs in metrics, not readiness.
  • Octane, Horizon, queues. Octane (FrankenPHP, Swoole, RoadRunner) keeps workers alive, so in-memory metrics become possible but per-worker; queue workers should run with --max-jobs and --memory so they exit before the container's memory limit and avoid OOMKilled restarts.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Evidence gone by the time someone looksExport Events and logsOTel k8sobjects (gateway) + node agent to LokiIncidents older than 1 h can be investigatedStorage and one more component
Crash loops with no visible error--previous + termination messageterminationMessagePolicy: FallbackToLogsOnError, kubectl logs --previousCause visible in describeOnly the last 2048 bytes / 80 lines
Distroless image cannot be inspectedEphemeral containerkubectl debug --target, RBAC for pods/ephemeralcontainersNo rebuild, no restartCannot be removed from the Pod
ServiceMonitor ignoredMatch the Prometheus selectorsrelease: RELEASE label, namespace selectors {}Teams self-serve scrapingOne more label to remember
Alert noiseAlert on RED symptoms, show USE causes on dashboardsRecording rules + for: + inhibitionFewer, actionable pagesNeeds instrumented services
Loki or Prometheus overloadedBound label cardinalityRoute patterns, structured metadata, metricRelabelings dropStable costLess ad hoc slicing
Duplicated cluster metrics/eventsSingle-replica gateway for cluster receiversmode: deployment, replicaCount: 1No duplicatesThat one Pod is a single point of collection
Requests fail but Pods are fineWalk Service → EndpointSlice → Pod → policyThe runbook's svc modeFinds selector and port mistakes in minutesNeeds a debug Pod for the network steps
OOMKilled surprisesAlert near the limit; size from working setContainerMemoryNearLimit, container_oom_events_totalWarned before the killSpikes shorter than a scrape stay invisible
On-call cannot debug at 03:00Pre-granted debugger role + runbookoncall-debugger ClusterRole, k8s-triage.shSame steps for everyoneMust be reviewed like any privilege

Export Events before they expire ​

Run one exporter, not several: either the OpenTelemetry gateway with the kubernetesEvents preset (Events land in the logs pipeline next to application logs) or the Resmo kubernetes-event-exporter routing Warning events to Slack and everything to the log store. Keep the gateway at one replica; a second one doubles every Event.

Make crashes explain themselves ​

Write a final structured error line before exiting (the Go service logs "msg":"exit","err":...), set terminationMessagePolicy: FallbackToLogsOnError, and read kubectl describe before kubectl logs. For Go panics the stack trace goes to stderr, which the runtime captures like stdout.

Debug without changing the image ​

Grant pods/ephemeralcontainers, use kubectl debug -it POD --image=nicolaka/netshoot:v0.17 --target=CONTAINER, and remember that Pod Security admission evaluates ephemeral containers too: in a restricted namespace use --profile=restricted.

Get every team's metrics into Prometheus ​

Standardise: Services name the port metrics; ServiceMonitors carry release: kube-prometheus-stack; Prometheus selects all namespaces (serviceMonitorNamespaceSelector: {}); NetworkPolicies allow the monitoring namespace to that port. Validate in CI: lint rules with promtool check rules in GitHub Actions or GitLab CI, and let Argo CD (or Flux) deploy the monitoring objects with the app; the stack itself is often installed by Terraform's Helm provider or by the same GitOps repository.

Keep observability affordable ​

Count series per job (count by (job) ({__name__=~".+"})), drop what nobody graphs with metricRelabelings, keep Loki labels to namespace, app, container and level, move ids to structured metadata, and set retention per signal (metrics 10–30 days in Prometheus, longer in a remote store; logs by compliance need).

Find a Service that routes nowhere ​

k8s-triage.sh svc NS NAME prints the selector, the EndpointSlices, the Pods matching the selector and the NetworkPolicies; an empty ENDPOINTS column plus Pods that exist means a selector or readiness problem, endpoints plus timeouts means policy or CNI.

Size memory from evidence ​

Plot max_over_time(container_memory_working_set_bytes[1d]) per container for a week, set the limit above the peak with headroom, set the request near the typical value, and watch ContainerMemoryNearLimit after each release. VPA in recommendation mode does the same arithmetic (see Resources, Scheduling & Autoscaling).

Choosing ​

Which debugging access ​

SituationUseWhy
Image has a shell, problem is livekubectl execFastest
Distroless or minimal imagekubectl debug --target with netshoot or busyboxShares network and process namespaces
Crashes on startkubectl debug --copy-to ... -- shInspect before the process exits
Need a debug buildkubectl debug --copy-to --set-imageProduction Pod untouched
Node-level issuekubectl debug node/NAME (--profile=sysadmin for chroot /host and tcpdump)Host namespaces, /host
Reach a Pod from a laptopkubectl port-forwardNo Ingress needed; one Pod only

Which metrics setup ​

ClusterRecommendationExtraReason
Any cluster with HPAmetrics-server—The Metrics API for autoscaling and kubectl top
Single cluster, self-managed monitoringkube-prometheus-stack via HelmPersistent storage for Prometheus, Grafana dashboards from ConfigMapsOperator, rules, dashboards in one chart
Many clustersPrometheus or Prometheus Agent per cluster + remote write to Thanos, Mimir or a managed serviceRecording rules close to the dataGlobal queries and long retention
Managed cloud (EKS, GKE, AKS)Provider's managed Prometheus or the chartControl-plane metrics from the providerYou may not be able to scrape etcd or the scheduler
Everything through OpenTelemetryOTel Collector (agent + gateway) with Prometheus receiver or OTLP metricsTarget Allocator for Prometheus scraping at scaleOne pipeline for all signals

Which log agent ​

NeedPickNotes
Logs only, small footprintFluent Bit (DaemonSet)kubernetes filter, Merge_Log, Loki/Elasticsearch outputs
Transformations, routing, metrics from logsVectorkubernetes_logs source; VRL transforms
Logs, metrics and traces in one agentOpenTelemetry CollectorHelm presets for Kubernetes; otlp_http exporter
Grafana stack end to endGrafana AlloySame DaemonSet pattern
Vendor (Datadog, Elastic, New Relic)The vendor agentUsually a DaemonSet plus a cluster agent

Which log backend ​

BackendIndexesBest forCost driver
LokiLabels only; content scanned at query timeCheap retention, Grafana users, kubectl logs-style queriesStream count (labels) and query volume
Elasticsearch / OpenSearchFull textFree-text search, analytics on fieldsIndex size and memory
Cloud logging (CloudWatch, Cloud Logging, Azure Monitor)Provider-specificManaged clusters, complianceIngest per GB

In architecture: from a single process to a distributed system ​

Observability in Kubernetes changes shape with the system: one Deployment needs kubectl and a few alerts; a platform of many teams needs conventions, self-service objects and a cost budget.

Monolith: one Deployment, one database ​

A Laravel monolith in one namespace: php-fpm, Nginx and the php-fpm exporter in one Pod, a queue worker Deployment, a managed database. kube-prometheus-stack, one PodMonitor, three alerts (error ratio, latency, PodCrashLooping) and Fluent Bit to Loki are enough. Troubleshooting is the method plus kubectl logs deploy/shop-web -c app --previous. The correlation id in Context ties a web request to the job it dispatched.

Modular monolith: one cluster, several teams ​

The same cluster now runs the shop, the back office and a reporting module owned by different teams. Each namespace has its own ServiceMonitors, PrometheusRules and AlertmanagerConfig (routes are scoped to the namespace by the OnNamespace matcher strategy), its own Grafana folder, and the shared platform team owns the stack, the node agent and the debugger role. Label conventions (app.kubernetes.io/name, team) are what make per-team dashboards possible.

Microservices: many services, one request ​

Checkout calls orders (Go), payments and stock. A slow checkout is no longer visible in one Pod's logs:

text
1  ingress-nginx: POST /checkout   traceparent 00-4bf9...-a1...-01   X-Request-ID abc-123
2  checkout (Laravel) -> orders-api (Go) GET /orders/42      same traceparent, new span
3  orders-api -> postgres 230 ms                              span + RED histogram bucket le="0.25"
4  orders-api log line: {"msg":"request","correlation_id":"abc-123","trace_id":"4bf9...","status":200}
5  Tempo: one trace with 4 spans; Grafana jumps from the latency panel to the trace,
   and from the trace to Loki lines with trace_id=4bf9...

What survives the service boundary is only what you propagate: traceparent (W3C Trace Context) and the correlation id header. Each service exposes its own RED metrics; dashboards show one row per service; alerts fire on the service users call (checkout), and the others are drill-downs. The OpenTelemetry gateway can do tail sampling so slow and failed traces are always kept.

Distributed data: many clusters, regions and backends ​

With a cluster per region, each runs Prometheus (or Prometheus Agent) with an external_labels cluster name and remote-writes to Thanos, Mimir or a managed store; Loki and Tempo are multi-tenant with a tenant per cluster or team (Fluent Bit's tenant_id). Alertmanager runs as a cluster so two regions do not page twice. The failure modes move: a partition between a cluster and the central store produces gaps, so each cluster keeps local retention, and alerts that must survive a partition are evaluated locally. Events and audit logs are exported per cluster, labelled with the cluster name, because kubectl sees only one cluster at a time.

Scaling path: 1×, 10×, 100× ​

ScaleMetricsLogs and tracesTroubleshooting
1× (one cluster, a few services)kube-prometheus-stack, defaultsFluent Bit → Loki single binarykubectl, the runbook script, k9s
10× (several teams)Per-team ServiceMonitors and rules, recording rules, metricRelabelingsOTel agent + gateway, Loki with object storage, TempoDebugger role, exported Events, runbook per alert
100× (many clusters, regions)Prometheus Agent + remote write, sharding, cardinality budgets per teamMulti-tenant Loki/Tempo, sampling, retention tiersCentral Grafana, cluster label everywhere, game days

Lab ​

Steps 1–3 ran on the build host (macOS, Go 1.27.4, kubectl v1.36.1 client, no cluster). Steps 4–9 need a cluster (kind, k3d, minikube or a managed one) and are expected, not run: the commands are real, the outputs are the documented shape with placeholders, never captured output.

1. Build and test the Go service (ran on the host) ​

All lab commands run from the snippet root: cd docs/snippets/platform/kubernetes-observability-troubleshooting (it holds go/, k8s/, runbook/, laravel-app/).

bash
cd docs/snippets/platform/kubernetes-observability-troubleshooting
(cd go && gofmt -l . && go vet ./... && go test -race -count=1 ./...)
# ok  	academy/kubernetes-observability-troubleshooting/before	1.348s
# ok  	academy/kubernetes-observability-troubleshooting/observe	1.436s
# ok  	academy/kubernetes-observability-troubleshooting/service	1.671s

Eight tests: the raw-path counter makes 100 series for 100 ids, the route label makes one, the JSON lines carry the correlation and trace ids, an unsafe id is replaced, 5xx log at ERROR, /metrics shows the RED series, readiness follows its flag, and after cancellation /readyz answers 503 while the app port still serves until the drain delay ends.

2. Metrics, JSON logs, the correlation id and the drain (ran on the host) ​

The commands and output below are copied from the saved run (time fields removed from the log lines; ... marks omitted lines).

bash
(cd go && go build -o ../orders-api ./service)
APP_ADDR=127.0.0.1:18080 METRICS_ADDR=127.0.0.1:19090 SHUTDOWN_DELAY=1s ./orders-api > service.log &
PID=$!
curl -s -i -H "X-Request-ID: lab-0001" 127.0.0.1:18080/orders/42 | grep -v "^Date:"
# HTTP/1.1 200 OK
# Content-Type: application/json
# X-Request-Id: lab-0001
# Content-Length: 28
#
# {"id":"42","status":"paid"}
curl -s -o /dev/null -w "%{http_code}\n" 127.0.0.1:18080/orders/fail     # 500
curl -s -o /dev/null -w "%{http_code}\n" 127.0.0.1:18080/orders/0        # 404
curl -s -o /dev/null -w "%{http_code}\n" 127.0.0.1:19090/readyz          # 200
curl -s 127.0.0.1:19090/metrics | grep -E "^http_requests_total|^http_request_duration_seconds_count|^http_requests_in_flight"
# http_request_duration_seconds_count{code="200",method="get",route="/orders/{id}"} 1
# http_request_duration_seconds_count{code="404",method="get",route="/orders/{id}"} 1
# http_request_duration_seconds_count{code="500",method="get",route="/orders/{id}"} 1
# http_requests_in_flight 0
# http_requests_total{code="200",method="get",route="/orders/{id}"} 1
# http_requests_total{code="404",method="get",route="/orders/{id}"} 1
# http_requests_total{code="500",method="get",route="/orders/{id}"} 1
curl -s -o /dev/null -w "%{http_code}\n" 127.0.0.1:18080/metrics         # 404: not on the app port
curl -s -H "Accept: application/openmetrics-text" 127.0.0.1:19090/metrics | grep -E "^# TYPE http_requests|^# EOF"
# # TYPE http_requests_in_flight gauge
# # TYPE http_requests counter
# # EOF
kill -TERM $PID; curl -s -o /dev/null -w "readyz during drain: %{http_code}\n" 127.0.0.1:19090/readyz; wait $PID; echo "exit=$?"
# readyz during drain: 503
# exit=0
cat service.log
# {"level":"INFO","msg":"listening","addr":"127.0.0.1:19090"}
# ...
# {"level":"INFO","msg":"request","correlation_id":"lab-0001","method":"GET","path":"/orders/42","status":200,"duration_ms":0}
# {"level":"ERROR","msg":"order store unavailable","correlation_id":"f4dfbe28af7e817d6f6a0ee41093a8b9","order_id":"fail"}
# {"level":"ERROR","msg":"request","correlation_id":"f4dfbe28af7e817d6f6a0ee41093a8b9","method":"GET","path":"/orders/fail","status":500,"duration_ms":0}
# ...
# {"level":"INFO","msg":"draining","delay":"1s"}
# {"level":"INFO","msg":"shutting down"}

The caller's id is echoed; requests without one get a generated id that appears on both the handler's line and the access line. During the drain /readyz already says 503 while requests are still answered; the delay gives kube-proxy and Ingress controllers time to stop routing to a terminating Pod before its listeners close.

3. The runbook script and the rules, without a cluster (ran on the host) ​

bash
bash -n runbook/k8s-triage.sh && echo syntax ok        # syntax ok
./runbook/k8s-triage.sh; echo "exit=$?"                 # prints usage, exit=2
KUBECONFIG=/dev/null KUBECTL=~/.docker/bin/kubectl ./runbook/k8s-triage.sh cluster
# ===== API server health =====
# $ kubectl get --raw=/livez
# The connection to the server localhost:8080 was refused - did you specify the right host or port?
# (exit 1)
# ... every section runs, each failure is printed and the script continues

Separately, every expr in prometheusrule.yaml was parsed with the Prometheus v0.316.0 PromQL parser in a scratch Go module: 15 of 15 parse.

4. Prerequisites: a cluster, the image and the stack (expected, not run) ​

bash
kind create cluster --name obs
kubectl create namespace shop
# Build the Go service image with the multi-stage pattern from Images & Dockerfiles:
cat > Dockerfile.orders <<'EOF'
FROM golang:1.27-trixie AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /orders-api ./service
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /orders-api /orders-api
ENTRYPOINT ["/orders-api"]
EOF
docker build -f Dockerfile.orders -t ghcr.io/example/orders-api:1.4.2 go   # build context: the go/ module
kind load docker-image ghcr.io/example/orders-api:1.4.2 --name obs
# The values file needs a Grafana admin Secret and uses the cluster's default StorageClass (kind: "standard")
kubectl create namespace monitoring
kubectl -n monitoring create secret generic grafana-admin \
  --from-literal=admin-user=admin --from-literal=admin-password="$(openssl rand -hex 16)"
kubectl get storageclass                 # expected on kind: standard (default)
helm install kube-prometheus-stack oci://ghcr.io/prometheus-community/charts/kube-prometheus-stack \
  -n monitoring --create-namespace -f k8s/kube-prometheus-stack-values.yaml
kubectl -n monitoring get pods
# expected shape: alertmanager-..., prometheus-..., kube-prometheus-stack-operator-...,
#                 kube-prometheus-stack-grafana-..., kube-state-metrics-..., one node-exporter per node
kubectl apply -f k8s/orders-api.yaml -f k8s/servicemonitor.yaml -f k8s/prometheusrule.yaml
kubectl -n monitoring port-forward svc/kube-prometheus-stack-prometheus 9090:9090
# expected: Status > Targets lists the shop/orders-api ServiceMonitor with 3 endpoints UP

5. Break it four ways and read the evidence (expected, not run) ​

bash
# a) an image that does not exist
kubectl -n shop set image deploy/orders-api orders-api=ghcr.io/example/orders-api:does-not-exist
kubectl -n shop get pods            # expected: new Pod ErrImagePull, then ImagePullBackOff
kubectl -n shop events --types=Warning
kubectl -n shop rollout undo deploy/orders-api
# b) a Secret key that does not exist
kubectl -n shop create secret generic shop-db --from-literal=password=s3cret
kubectl -n shop patch deploy orders-api --type=json -p '[{"op":"add","path":"/spec/template/spec/containers/0/env/-",
  "value":{"name":"DB_PASSWORD","valueFrom":{"secretKeyRef":{"name":"shop-db","key":"pasword"}}}}]'
kubectl -n shop get pods            # expected: CreateContainerConfigError
kubectl -n shop events --types=Warning | grep "couldn't find key"
kubectl -n shop rollout undo deploy/orders-api
# c) a crash on start (invalid listen address)
kubectl -n shop set env deploy/orders-api APP_ADDR=:-1
kubectl -n shop logs deploy/orders-api --previous     # expected: the JSON "exit" line with the listen error
kubectl -n shop describe pod -l app.kubernetes.io/name=orders-api | grep -A4 "Last State"
kubectl -n shop rollout undo deploy/orders-api
# d) OOMKilled, with the Kubernetes docs' own example (stress allocates 250M against a 100Mi limit)
kubectl create namespace mem-example
kubectl apply -f https://k8s.io/examples/pods/resource/memory-request-limit-2.yaml --namespace=mem-example
kubectl -n mem-example get pod memory-demo-2 -o yaml | grep -A4 "lastState\|terminated"
# documented output: exitCode: 137, reason: OOMKilled

6. Debug a distroless Pod (expected, not run) ​

bash
POD=$(kubectl -n shop get pod -l app.kubernetes.io/name=orders-api -o name | head -1)
kubectl -n shop exec -it $POD -- sh                   # expected: executable file not found
kubectl -n shop debug -it $POD --image=nicolaka/netshoot:v0.17 --target=orders-api
# inside: curl -s localhost:9090/metrics | head; dig +search kube-dns.kube-system; cat /etc/resolv.conf
kubectl -n shop describe $POD | grep -A3 "Ephemeral Containers"

7. Service and DNS (expected, not run) ​

bash
kubectl -n shop patch svc orders-api -p '{"spec":{"selector":{"app.kubernetes.io/name":"orders"}}}'
kubectl -n shop get endpointslices -l kubernetes.io/service-name=orders-api     # ENDPOINTS <none>
./runbook/k8s-triage.sh svc shop orders-api
kubectl -n shop patch svc orders-api -p '{"spec":{"selector":{"app.kubernetes.io/name":"orders-api"}}}'
./runbook/k8s-triage.sh dns
kubectl run dns-test -n shop --rm -it --restart=Never --image=nicolaka/netshoot:v0.17 -- \
  sh -c 'cat /etc/resolv.conf; dig +search orders-api +short; dig api.stripe.com. +short'
# expected: search shop.svc.cluster.local svc.cluster.local cluster.local / options ndots:5

8. Logs and Events pipeline (expected, not run) ​

This step needs three things this chapter's snippets do not provide: a Loki installation reachable as loki-gateway.observability.svc (both the Fluent Bit output and the OTel gateway point there), a Tempo service tempo.observability.svc and an OTLP metrics store metrics-backend.observability.svc for the gateway's other exporters, and a Loki datasource in Grafana (for kube-prometheus-stack, through the chart's Grafana additional datasources). Without them the collectors run but the Explore query below returns nothing.

bash
helm install fluent-bit fluent/fluent-bit -n observability --create-namespace -f k8s/fluent-bit-values.yaml
helm install otel-gateway open-telemetry/opentelemetry-collector -n observability -f k8s/otel-gateway-values.yaml
# Grafana Explore, Loki:  {namespace="shop", app="orders-api"} | json | level="ERROR"
# Events arrive through the gateway's k8sobjects receiver; delete a Pod and look for "Killing"

9. Node and control plane (expected, not run) ​

bash
kubectl get --raw='/readyz?verbose' | tail -3      # ... healthz check passed
NODE=$(kubectl get nodes -o name | head -1 | cut -d/ -f2)
kubectl debug node/$NODE -it --profile=sysadmin --image=busybox:1.37 -- chroot /host sh -c 'df -h /var; journalctl -u kubelet --since -10m | tail'
kubectl get pods -A -o name | grep node-debugger | xargs kubectl delete    # clean up the debug Pod

Common misconceptions ​

BeliefReality
kubectl logs shows the crashThe crash is in --previous; only one terminated container is kept
Events are historyDeduplicated, best-effort, deleted after --event-ttl (1 h by default)
metrics-server is monitoring"meant only for autoscaling purposes"; latest values only
kube-state-metrics measures usageIt exports object state; usage comes from cAdvisor
A ServiceMonitor is enough to be scrapedPrometheus must select it (release label in kube-prometheus-stack) and the port is a name
Exit code 137 always means OOM137 is SIGKILL; check reason: OOMKilled (liveness kills and grace-period kills are also 137)
CPU limits protect latencyThey cause CFS throttling; requests protect scheduling
kubectl port-forward svc/x tests the ServiceIt forwards to one selected Pod and ends when that Pod terminates
Force-delete fixes TerminatingForce does not remove finalizers, so a finalizer-blocked object stays; for a Pod without finalizers it skips the kubelet's confirmation and the process may survive
More CoreDNS replicas fix slow DNSOften the search list and ndots:5 multiply queries; use FQDNs with a trailing dot or lower ndots
More collector replicas are saferCluster-wide receivers duplicate data with more than one replica
Pod name and request id make good Loki labelsUnbounded labels explode streams; use structured metadata
Readiness should check every dependencyA shared dependency failure then removes every Pod from the Service
/healthz is the API server health checkDeprecated since v1.16; use /livez and /readyz

Cheat sheet ​

TopicRemember
MethodObject → events → describe → logs (--previous) → exec/debug → node
Eventskubectl events --for pod/NAME --types=Warning; gone after 1 h; export them
Logskubectl logs -l app=X --all-containers --prefix --since=15m; -p after restarts
RotationcontainerLogMaxSize 10Mi × containerLogMaxFiles 5; kubectl logs reads the newest file
CRI formatTIMESTAMP stdout F message; P = partial line
Debugkubectl debug -it POD --image=nicolaka/netshoot --target=C; debug node/N mounts /host
Metric sourcescAdvisor = usage, kube-state-metrics = state, node-exporter = host, metrics-server = autoscaling
Operator objectsServiceMonitor (Service, port name), PodMonitor (Pods), PrometheusRule, AlertmanagerConfig
kube-prometheus-stackLabel objects release: RELEASE; CRDs not upgraded by Helm
Key serieskube_pod_status_phase, ..._waiting_reason, ..._last_terminated_reason, container_memory_working_set_bytes, container_cpu_cfs_throttled_periods_total
SignalsRED for services (alert), USE for resources (diagnose)
CollectorDaemonSet for node-local receivers, one-replica Deployment for cluster receivers
Back-offsCrashLoopBackOff 10 s doubling to 300 s, reset after 10 min; ImagePullBackOff up to 300 s
Exit codes1 app, 2 Go panic, 137 SIGKILL/OOM, 143 SIGTERM
Service checkskubectl get endpointslices -l kubernetes.io/service-name=NAME; selector, targetPort, policy
DNSsearch ... options ndots:5; trailing dot for external names; CoreDNS -l k8s-app=kube-dns
Control planekubectl get --raw='/readyz?verbose'; etcdctl endpoint health

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A Pod shows RESTARTS 7 and CrashLoopBackOff. kubectl logs prints a normal startup line. Where is the error, and what else do you read? Must-know ​

Answer

Answer: The plain command shows the current container, which has just started. The crash is in kubectl logs POD --previous (one terminated container is kept). Also read kubectl describe pod for Last State: Terminated, the exit code and the termination message, and the Events for probe failures (Unhealthy) that may be killing it. See CrashLoopBackOff.

2 — A Pod has been Pending for 20 minutes. What do you run first, and name three reasons the answer might give. Must-know ​

Answer

Answer: kubectl describe pod or kubectl events --for pod/NAME, looking for FailedScheduling. Its message has the shape "0/X nodes are available: ..." with reasons such as Insufficient cpu/memory, node(s) had untolerated taint(s), node(s) didn't match Pod's node affinity/selector, or pod has unbound immediate PersistentVolumeClaims. Logs are useless here because the container never ran.

3 — What is the difference between metrics-server, kube-state-metrics, node-exporter and cAdvisor? Must-know ​

Answer

Answer: cAdvisor, built into the kubelet, measures per-container usage (container_*). node-exporter (DaemonSet, port 9100) measures the host (node_*). kube-state-metrics watches the API and exports object state (kube_pod_status_phase, waiting reasons, conditions), not usage. metrics-server scrapes kubelets every 15 s and serves only the latest CPU and memory through the Metrics API for HPA, VPA and kubectl top; its README says not to use it for monitoring.

4 — A container's last state is OOMKilled with exit code 137. What happened, and how do you prevent the next one? Must-know ​

Answer

Answer: The kernel's OOM killer sent SIGKILL (128 + 9 = 137) and the kubelet restarted the container. Usually the container exceeded its own memory limit (its cgroup); but if the node ran out of memory before the kubelet could evict, the node-wide OOM killer may have chosen this container by OOM score (BestEffort and low-request Burstable first) even below its limit, so compare its working set with the limit and look at node memory. For a limit OOM, size the limit from container_memory_working_set_bytes peaks plus headroom, alert at 90 % of the limit, look for leaks, and for workers exit before the limit (queue:work --memory, bounded caches). Exit 137 without OOMKilled is a different SIGKILL, for example after a failing liveness probe.

5 — Every Pod of a Deployment is Running and Ready, but the Ingress returns 503. Walk through your checks. Must-know ​

Answer

Answer: kubectl get endpointslices -l kubernetes.io/service-name=NAME: if ENDPOINTS is empty, compare the Service spec.selector with the Pod labels (selector mismatch) and targetPort with the container port. If endpoints exist, curl a Pod IP and port directly from a netshoot Pod, then the Service name (DNS), then check NetworkPolicies (timeouts point to a drop). Finally the Ingress controller's own logs.

6 — You applied a ServiceMonitor, but Prometheus (installed with kube-prometheus-stack) shows no target. Name the likely causes. Important ​

Answer

Answer: The ServiceMonitor lacks the release: RELEASE label that the chart's serviceMonitorSelector requires by default (serviceMonitorSelectorNilUsesHelmValues: true); Prometheus does not watch its namespace (serviceMonitorNamespaceSelector); its selector matches the Pods' labels but not the Service's labels; endpoints[].port names a port the Service does not have (it is a name, not a number); or a NetworkPolicy blocks the scrape (target then shows DOWN, not missing).

7 — Why can an OpenTelemetry Collector that collects logs not run as a 3-replica Deployment, and why can the one that collects Events not run as a DaemonSet? Important ​

Answer

Answer: The filelog and kubeletstats receivers read node-local data, so a Deployment only collects from the nodes its replicas happen to run on; they belong in a DaemonSet (agent). The k8sobjects (Events) and k8s_cluster receivers read the whole cluster from the API server, so every extra instance, whether a DaemonSet Pod or a replica, duplicates the data; they belong in a single-replica Deployment (gateway).

8 — How do you get a shell-like view into a distroless container, and what permission does it need? Important ​

Answer

Answer: kubectl debug -it POD --image=busybox:1.37 --target=CONTAINER adds an ephemeral container that shares the Pod's network namespace and, with --target, the container's process namespace (/proc/1/root shows its files). It needs update/patch on pods/ephemeralcontainers, which the built-in edit and admin roles do not grant. The ephemeral container cannot be removed and is subject to Pod Security admission; choose --profile accordingly.

9 — Your on-call engineer is paged at 09:00 for a crash at 03:00 and finds no Events. Why, and what platform change fixes it? Important ​

Answer

Answer: The API server deletes Events after --event-ttl, default one hour. Export Events continuously, with the OpenTelemetry Collector's k8sobjects receiver (one instance) or a maintained event exporter, into the log backend, and keep metrics (kube-state-metrics restarts and waiting reasons) that record the state change independently.

10 — An external API call from a Pod takes several extra DNS round trips. Explain ndots:5 and give two fixes. Important ​

Answer

Answer: With options ndots:5, a name with fewer than five dots is first tried with every search suffix (NS.svc.cluster.local, svc.cluster.local, cluster.local), each returning NXDOMAIN, before the name itself; with A and AAAA that is many queries. Fix by writing the FQDN with a trailing dot (api.stripe.com.) or by setting dnsConfig.options ndots: "2" for that Pod; also check CoreDNS logs and its kube-dns Service if lookups fail entirely.

11 — Why does the Go service label requests with the route pattern and serve /metrics on a separate port? Good to know ​

Answer

Answer: Every label value combination is a series; the raw path creates one per order id (the before test shows 100 series for 100 ids), the ServeMux pattern /orders/{id} creates one. A separate admin port keeps /metrics and the probes off the public Ingress and out of the RED counters, and lets the ServiceMonitor and NetworkPolicy target one named port.

12 — How does a Laravel app on php-fpm expose RED metrics and JSON logs that a Kubernetes log pipeline can use? Good to know ​

Answer

Answer: Logs: the skeleton's stderr channel with LOG_STDERR_FORMATTER=Monolog\Formatter\JsonFormatter, never files under storage/logs; a correlation id added with Context::add appears on every line and in queued jobs. Metrics: php-fpm workers share nothing, so promphp stores counters in APCu (per Pod) or Redis, labelled by route URI; the php-fpm exporter sidecar (port 9253) reads pm.status_path for pool saturation (phpfpm_listen_queue, phpfpm_max_children_reached).

13 — A namespace has been Terminating for an hour. What is going on, and what is the risk of the quick fix? Must-know ​

Answer

Answer: Deletion waits until every finalizer on the namespace and on the objects in it is removed by its controller; the namespace status conditions name what remains (content or finalizers), often a custom resource whose operator was uninstalled, or a webhook blocking updates. Reinstalling the controller lets cleanup finish; patching the finalizer away is quick but skips that cleanup (cloud load balancers, volumes, DNS records stay behind).

Glossary ​

TermMeaning
troubleshooting methodThe fixed order: symptom, object, events, describe, logs, exec/debug, node
kubectl describeHuman-readable state of an object including recent Events
kubectl get eventsLists Event objects; sort with --sort-by=.lastTimestamp
kubectl eventsNewer command: --for, --types, --watch, oldest first
EventAPI object with type, reason, note, regarding object, reporting controller
Warning eventsEvents of type Warning; the ones to read first
event TTL--event-ttl on kube-apiserver, default 1h; Events are deleted after it
event exporterA controller that copies Events to a log backend or chat
FailedSchedulingScheduler event reason when no node fits a Pod
kubectl logsReads a container's log through the API server and kubelet
--previouskubectl logs flag: the previous instance of the container
--sincekubectl logs flag: only lines newer than a duration
-l selectorkubectl logs -l key=value: logs of all matching Pods (max 5 streams by default)
--all-containerskubectl logs flag: every container in the Pod
CRI log formatRFC3339Nano stream P/F message lines written by the runtime
log rotation containerLogMaxSizeKubelet setting (10Mi) that, with containerLogMaxFiles (5), rotates container logs
kubectl execRuns a command in an existing container
kubectl debugAdds an ephemeral container, copies a Pod, or starts a node debug Pod
ephemeral containerTemporary container added to a running Pod; no ports, probes or resources; not restarted
debug nodekubectl debug node/NAME: Pod with host namespaces, node root at /host
debugging profile--profile general, baseline, restricted, netadmin, sysadmin
netshootNetwork troubleshooting image with curl, dig, tcpdump, iperf3
kubectl port-forwardLocal port tunnelled to one Pod through the API server
kubectl topLive CPU/memory from the Metrics API
metrics-serverAdd-on feeding the Metrics API for autoscaling, every 15 s
kube-state-metricsExports object state as Prometheus metrics (port 8080)
node-exporterHost metrics exporter, DaemonSet, port 9100
cAdvisorContainer usage metrics built into the kubelet
kube_pod_status_phasekube-state-metrics gauge per Pod and phase
container_memory_working_set_bytescAdvisor memory that counts toward limits and eviction
container_cpu_cfs_throttledcontainer_cpu_cfs_throttled_periods_total / _seconds_total: CPU limit throttling
Prometheus OperatorOperator turning CRDs into Prometheus and Alertmanager config
ServiceMonitorCRD selecting Services and their endpoints to scrape by port name
PodMonitorCRD selecting Pods to scrape directly
PrometheusRuleCRD holding recording and alerting rules
AlertmanagerGroups, inhibits, silences and routes alerts; also a CRD
AlertmanagerConfigNamespaced CRD with routes, receivers, inhibit rules
kube-prometheus-stackHelm chart: operator, Prometheus, Alertmanager, Grafana, kube-state-metrics, node-exporter
GrafanaDashboards and exploration for metrics, logs and traces
USE methodUtilization, saturation, errors for every resource
RED methodRate, errors, duration for every service
recording rulePrecomputed PromQL stored as a new series
cardinalityNumber of distinct label combinations, i.e. series or streams
OpenTelemetry CollectorVendor-neutral agent/gateway for logs, metrics and traces
DaemonSet vs Deployment collectorAgent per node for node-local receivers; one gateway replica for cluster receivers
k8sattributes processorAdds Pod, namespace and node metadata to telemetry
otlp_httpCurrent name of the OTLP/HTTP exporter (otlphttp is a deprecated alias)
Fluent BitLightweight log agent; tail + kubernetes filter
VectorLog/metrics pipeline with a kubernetes_logs source
LokiLog store indexing labels only
structured metadataLoki per-line fields for high-cardinality values
TempoDistributed tracing backend, TraceQL
PendingPod phase before scheduling and volume binding complete
ImagePullBackOffWaiting between failed image pulls, up to 300 s
ErrImagePullWaiting reason after a failed pull attempt
CreateContainerConfigErrorKubelet could not build the container config (missing ConfigMap/Secret/key)
CrashLoopBackOffWaiting between restarts of a crashing container, 10 s doubling to 300 s
OOMKilledTermination reason when the kernel OOM killer killed the container (limit exceeded, or node-wide OOM)
exit code 137128 + SIGKILL(9); OOM kill or forced kill
readiness probe failingPod running but removed from endpoints; Unhealthy events
Terminating stuckDeletion waiting for finalizers or blocked by a webhook
finalizersKeys on an object that its controller must remove before deletion completes
EvictedPod terminated by the kubelet under node pressure
node pressureMemoryPressure, DiskPressure, PIDPressure conditions
NodeNotReadyNode Ready condition false or unknown; event reason
CoreDNSCluster DNS server, label k8s-app=kube-dns, Service kube-dns
ndotsresolv.conf threshold of dots before an absolute lookup; 5 in Pods
DNS debuggingTest Pod, resolv.conf, CoreDNS Pods, logs, Service, EndpointSlices
EndpointSliceObject listing the ready and not-ready endpoints behind a Service
Service without endpointsService whose selector matches no ready Pod
selector mismatchService selector and Pod labels differ
NetworkPolicy dropTraffic denied by a policy; seen as a timeout
PVC PendingClaim not bound to a volume yet
API server health endpoints livez readyz/livez (restart?) and /readyz (serve?), /healthz deprecated
etcd healthetcdctl endpoint health; [+]etcd ok in /readyz?verbose
audit logAPI server record of requests at None/Metadata/Request/RequestResponse
kubectl pluginsExecutables named kubectl-* on PATH
krewPackage manager for kubectl plugins
sternMulti-Pod log tailing tool
k9sTerminal UI for Kubernetes
kubectl-neatStrips clutter from manifests; unmaintained
runbookAlert-linked procedure: meaning, confirm, mitigate, escalate
on-callRota responsible for responding to pages
promhttp /metricsclient_golang handler serving a registry in Prometheus/OpenMetrics format
Go metrics endpointThe service's /metrics on the admin port
php-fpm exporterhipages/php-fpm_exporter, reads the php-fpm status page, port 9253
Laravel JSON logsstderr channel with Monolog JsonFormatter
structured logging stdoutOne JSON object per line on stdout/stderr
correlation idRequest id propagated in headers and logged on every line
traceparentW3C Trace Context header carrying trace id and span id

References ​

Kubernetes documentation (kubernetes.io):

Metrics:

Logs and traces:

Debugging tools and DNS:

Go and Laravel:

Built by Morteza Negahi