Skip to content

Debug scripts: Kubernetes

6 paste-and-run bash scripts that collect what you need to find the error.

Index
6 items
  1. Paste the container ID, pod, service or URL into the box.
  2. Copy the script and paste it into a terminal on the machine (or where kubectl works).
  3. Read the report. It is also saved as debug-*.txt in the current folder to share.

Debug a pod (CrashLoopBackOff, Error, not Ready)

Read-only

Paste the pod and namespace. Shows every container's state and last crash reason, conditions, events, current and previous logs, errors, probes, resources and owner.

(
P="<pod>"; NS="<namespace>"
h() { printf '\n=== %s ===\n' "$*"; }
k() { kubectl -n "$NS" "$@"; }

h "Pod"
k get pod "$P" -o wide || { echo "No pod '$P' in namespace '$NS'. List them with: kubectl get po -n $NS"; exit 1; }

h "Container states (current and last termination)"
k get pod "$P" -o jsonpath='{range .status.initContainerStatuses[*]}init {.name}: ready={.ready} restarts={.restartCount}{"\n"}  state={.state}{"\n"}  last={.lastState}{"\n"}{end}{range .status.containerStatuses[*]}{.name}: ready={.ready} restarts={.restartCount}{"\n"}  state={.state}{"\n"}  last={.lastState}{"\n"}{end}'

h "Conditions"
k get pod "$P" -o jsonpath='{range .status.conditions[*]}{.type}={.status} {.reason} {.message}{"\n"}{end}'

h "Events for this pod"
k get events --field-selector involvedObject.name="$P" --sort-by=.lastTimestamp

h "Logs: last 50 lines (all containers)"
k logs "$P" --all-containers --prefix --tail=50 2>&1

h "Logs of the previous (crashed) containers"
k logs "$P" --all-containers --prefix --previous --tail=50 2>&1

h "Error lines in the last 2000 log lines"
ERR=$(k logs "$P" --all-containers --prefix --tail=2000 2>&1 | grep -iE 'error|exception|fatal|panic|refused|denied|timed? ?out|killed|no such|not found' | tail -25)
[ -n "$ERR" ] && echo "$ERR" || echo "no error-looking lines"

h "Images, resources and probes"
k get pod "$P" -o jsonpath='{range .spec.containers[*]}{.name}: image={.image}{"\n"}  requests={.resources.requests} limits={.resources.limits}{"\n"}  liveness={.livenessProbe}{"\n"}  readiness={.readinessProbe}{"\n"}{end}'

h "Current CPU and memory"
k top pod "$P" --containers 2>/dev/null || echo "metrics-server not available"

h "Owner and node"
k get pod "$P" -o jsonpath='owner: {.metadata.ownerReferences[0].kind}/{.metadata.ownerReferences[0].name}{"\n"}node: {.spec.nodeName}{"\n"}serviceAccount: {.spec.serviceAccountName}{"\n"}'
) 2>&1 | tee "debug-pod-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Podstatus, ready count, restarts, IP and node
  2. Container stateswaiting reason (CrashLoopBackOff, ImagePullBackOff, CreateContainerConfigError) and the last termination: reason (OOMKilled, Error), exit code, time
  3. ConditionsPodScheduled, Initialized, ContainersReady, Ready with the reason when false
  4. Eventsscheduling, image pulls, probe failures, kills, volume mount errors, in time order
  5. Logsthe last 50 lines of every container
  6. Previous logsoutput of the container that crashed, before Kubernetes restarted it
  7. Error lineserror, exception, refused, timeout... lines from recent logs
  8. Images, resources and probesimage tags, requests/limits (OOM if usage hits the limit) and probe settings (too-strict probes cause restarts)
  9. CPU and memorycurrent usage per container (needs metrics-server)
  10. Owner and nodewhich Deployment / StatefulSet / Job owns it, the node and the service account

Deployment rollout stuck or pods not becoming ready

Read-only

Paste the deployment and namespace. Shows rollout status and conditions, old vs new ReplicaSets, the pods that are not ready, related events, and the details and logs of the first broken pod.

(
D="<deployment>"; NS="<namespace>"
h() { printf '\n=== %s ===\n' "$*"; }
k() { kubectl -n "$NS" "$@"; }

h "Deployment"
k get deploy "$D" -o wide || { echo "No deployment '$D' in '$NS'. List them with: kubectl get deploy -n $NS"; exit 1; }

h "Rollout status (10s check)"
k rollout status deploy/"$D" --timeout=10s 2>&1

h "Conditions"
k get deploy "$D" -o jsonpath='{range .status.conditions[*]}{.type}={.status} {.reason}: {.message}{"\n"}{end}'

SEL=$(k get deploy "$D" -o go-template='{{range $k, $v := .spec.selector.matchLabels}}{{$k}}={{$v}},{{end}}'); SEL=${SEL%,}

h "ReplicaSets (new one should become ready, old ones scale to 0)"
k get rs -l "$SEL" -o wide

h "Pods"
k get pods -l "$SEL" -o wide

h "Pods that are not ready"
BAD=$(k get pods -l "$SEL" --no-headers | awk '{split($2, r, "/"); if (r[1] != r[2] || ($3 != "Running" && $3 != "Completed")) print $1}')
[ -n "$BAD" ] && echo "$BAD" || echo "all pods ready"

h "Recent events for the deployment, its ReplicaSets and pods"
k get events --sort-by=.lastTimestamp | grep -E "$D" | tail -30

FIRST=$(echo "$BAD" | head -1)
if [ -n "$FIRST" ]; then
  h "First broken pod: $FIRST (state and last events)"
  k get pod "$FIRST" -o jsonpath='{range .status.containerStatuses[*]}{.name}: state={.state} last={.lastState}{"\n"}{end}'
  k describe pod "$FIRST" | sed -n '/^Events:/,$p' | tail -15
  h "First broken pod: logs"
  k logs "$FIRST" --all-containers --prefix --tail=40 2>&1
fi

h "Rollout history"
k rollout history deploy/"$D" | tail -5
) 2>&1 | tee "debug-rollout-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Deploymentready / up-to-date / available replicas, images and selector
  2. Rollout statuswhether the rollout finishes (checked for 10 seconds only)
  3. ConditionsProgressing=False with ProgressDeadlineExceeded, or ReplicaFailure (quota, admission webhook)
  4. ReplicaSetsold vs new ReplicaSet and how many pods each has
  5. Pods not readypods with fewer ready containers than total, or not Running
  6. Eventsevents mentioning the deployment, its ReplicaSets and pods
  7. First broken podcontainer state, last events and logs of the first pod that is not ready
  8. Rollout historythe last revisions, for kubectl rollout undo

Service not reachable / has no endpoints

Read-only

Paste the service and namespace. Compares the service selector and ports with the pods behind it, shows endpoints and readiness, and prints a ready-to-run in-cluster curl test.

(
S="<service>"; NS="<namespace>"
h() { printf '\n=== %s ===\n' "$*"; }
k() { kubectl -n "$NS" "$@"; }

h "Service"
k get svc "$S" -o wide || { echo "No service '$S' in '$NS'. List them with: kubectl get svc -n $NS"; exit 1; }

h "Ports (service port -> targetPort)"
k get svc "$S" -o jsonpath='{range .spec.ports[*]}{.name} port {.port} -> targetPort {.targetPort} ({.protocol}){"\n"}{end}'

SEL=$(k get svc "$S" -o go-template='{{range $k, $v := .spec.selector}}{{$k}}={{$v}},{{end}}'); SEL=${SEL%,}
h "Selector"
echo "${SEL:-no selector: endpoints are managed by hand or by a controller}"

h "Endpoints (ready pod IPs behind the service)"
k get endpointslices -l kubernetes.io/service-name="$S" -o wide

if [ -n "$SEL" ]; then
  h "Pods matching the selector"
  k get pods -l "$SEL" -o wide --show-labels
  h "Readiness of those pods"
  k get pods -l "$SEL" -o jsonpath='{range .items[*]}{.metadata.name}: phase={.status.phase} ready={.status.containerStatuses[*].ready}{"\n"}{end}'
  h "Container ports of the first pod (targetPort must match one of these)"
  k get pods -l "$SEL" -o jsonpath='{range .items[0].spec.containers[*]}{.name}: {.ports}{"\n"}{end}'
fi

h "Ingresses pointing at this service"
k get ingress -o jsonpath='{range .items[*]}{.metadata.name}: {range .spec.rules[*]}{.host} {range .http.paths[*]}{.path}->{.backend.service.name}:{.backend.service.port.number}{.backend.service.port.name} {end}{end}{"\n"}{end}' | grep -w "$S" || echo "none"

h "Test it from inside the cluster (run this yourself)"
PORT=$(k get svc "$S" -o jsonpath='{.spec.ports[0].port}')
echo "kubectl run nettest --rm -it --restart=Never -n $NS --image=curlimages/curl -- curl -sv http://$S.$NS.svc.cluster.local:$PORT/"
) 2>&1 | tee "debug-service-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Servicetype, cluster IP, external IP and ports
  2. Portsservice port to targetPort mapping: targetPort must be the port the app listens on in the pod
  3. Selectorthe labels the service uses to find pods
  4. Endpointsempty means no ready pod matches the selector
  5. Pods matching the selectorif none show up, the labels differ (typo, wrong app label, wrong namespace)
  6. Readinesspods that are Running but not ready are left out of the endpoints (failing readiness probe)
  7. Container portscompare with targetPort
  8. Ingressesingress rules that route to this service, with host, path and port
  9. In-cluster testa curl command to run from a throwaway pod, to test the service DNS name and port directly

Pod stuck in Pending (can't be scheduled)

Read-only

Paste the pod and namespace. Shows the scheduler's reason, what the pod requests, free capacity per node, node taints, the pod's node selector / affinity / tolerations, and its volume claims.

(
P="<pod>"; NS="<namespace>"
h() { printf '\n=== %s ===\n' "$*"; }
k() { kubectl -n "$NS" "$@"; }

h "Pod"
k get pod "$P" -o wide || exit 1

h "Why the scheduler can't place it"
k get events --field-selector involvedObject.name="$P" --sort-by=.lastTimestamp | grep -iE 'FailedScheduling|NotTriggerScaleUp|TriggeredScaleUp|FailedAttach|FailedMount' || echo "no scheduling events yet"

h "What the pod asks for"
k get pod "$P" -o jsonpath='{range .spec.containers[*]}{.name}: requests={.resources.requests}{"\n"}{end}nodeSelector={.spec.nodeSelector}{"\n"}affinity={.spec.affinity}{"\n"}tolerations={.spec.tolerations}{"\n"}'

h "Allocated vs allocatable per node"
for n in $(kubectl get nodes -o name); do
  echo "--- $n"
  kubectl describe "$n" | sed -n '/Allocated resources/,/Events/p' | grep -E 'cpu|memory|pods' | head -3
done

h "Nodes: ready, taints, unschedulable"
kubectl get nodes -o custom-columns='NAME:.metadata.name,READY:.status.conditions[?(@.type=="Ready")].status,UNSCHEDULABLE:.spec.unschedulable,TAINTS:.spec.taints[*].key'

h "Volume claims used by the pod"
for c in $(k get pod "$P" -o jsonpath='{.spec.volumes[*].persistentVolumeClaim.claimName}'); do
  k get pvc "$c" -o wide
  k get events --field-selector involvedObject.name="$c" --sort-by=.lastTimestamp | tail -5
done

h "Namespace quotas"
k get resourcequota 2>/dev/null || true
) 2>&1 | tee "debug-pending-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Scheduler reasonFailedScheduling message: Insufficient cpu/memory, didn't match node selector, untolerated taint, unbound PVC
  2. What the pod asks forCPU/memory requests, nodeSelector, affinity and tolerations that limit where it can go
  3. Allocated vs allocatablerequested CPU/memory per node: Pending even with low usage means requests are too high
  4. Nodesready state, cordoned nodes and taints
  5. Volume claimsa PVC that is Pending blocks the pod (no StorageClass, wrong zone, capacity)
  6. Quotasa namespace ResourceQuota can block new pods

Namespace health: everything that's broken right now

Read-only

Paste a namespace. Lists pods that are not healthy, the most restarted containers, deployments missing replicas, unbound volume claims, warning events and the biggest resource users.

(
NS="<namespace>"
h() { printf '\n=== %s ===\n' "$*"; }
k() { kubectl -n "$NS" "$@"; }

h "Pods that are not Running/Completed or not fully ready"
k get pods --no-headers 2>/dev/null | awk '{split($2, r, "/"); if (($3 != "Running" && $3 != "Completed") || ($3 == "Running" && r[1] != r[2])) print}' | sed 's/^/  /'

h "Most restarted pods"
k get pods --no-headers | sort -k4 -rn | head -10

h "Deployments / StatefulSets missing replicas"
k get deploy,sts --no-headers 2>/dev/null | awk '{split($2, r, "/"); if (r[1] != r[2]) print}'

h "Volume claims not Bound"
k get pvc --no-headers 2>/dev/null | awk '$2 != "Bound"'

h "Jobs that failed"
k get jobs -o jsonpath='{range .items[?(@.status.failed)]}{.metadata.name}: failed={.status.failed}{"\n"}{end}' 2>/dev/null

h "Warning events (latest 30)"
k get events --field-selector type=Warning --sort-by=.lastTimestamp | tail -30

h "Top memory and CPU users"
k top pods --sort-by=memory 2>/dev/null | head -8 || echo "metrics-server not available"
k top pods --sort-by=cpu 2>/dev/null | head -8
) 2>&1 | tee "debug-namespace-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Unhealthy podsPending, CrashLoopBackOff, Error, ImagePullBackOff, or Running but not ready
  2. Most restarted podssorted by restart count: hidden crash loops
  3. Missing replicasdeployments and statefulsets with fewer ready pods than desired
  4. Volume claimsPVCs stuck in Pending or Lost
  5. Failed jobsjobs with failed pods (migrations, backups, cron jobs)
  6. Warning eventsthe latest problems Kubernetes reported in this namespace
  7. Top userspods using the most memory and CPU right now

Node NotReady or under pressure

Read-only

Paste a node name. Shows node conditions (memory, disk, PID pressure, Ready), taints, allocated resources, failing pods on that node, node events and usage.

(
N="<node>"
h() { printf '\n=== %s ===\n' "$*"; }

h "Node"
kubectl get node "$N" -o wide || { echo "No node '$N'. List them with: kubectl get nodes"; exit 1; }

h "Conditions"
kubectl get node "$N" -o jsonpath='{range .status.conditions[*]}{.type}={.status} {.reason}: {.message}{"\n"}{end}'

h "Taints and schedulability"
kubectl get node "$N" -o jsonpath='unschedulable={.spec.unschedulable}{"\n"}taints={.spec.taints}{"\n"}'

h "Allocated resources"
kubectl describe node "$N" | sed -n '/Allocated resources/,/Events/p'

h "Pods on this node that are not Running"
kubectl get pods -A -o wide --field-selector spec.nodeName="$N",status.phase!=Running

h "Node events"
kubectl get events -A --field-selector involvedObject.name="$N" --sort-by=.lastTimestamp | tail -20

h "Usage"
kubectl top node "$N" 2>/dev/null || echo "metrics-server not available"

h "Versions"
kubectl get node "$N" -o jsonpath='kubelet={.status.nodeInfo.kubeletVersion} runtime={.status.nodeInfo.containerRuntimeVersion} os={.status.nodeInfo.osImage} kernel={.status.nodeInfo.kernelVersion}{"\n"}'
) 2>&1 | tee "debug-node-$(date +%Y%m%d-%H%M%S).txt"
What it checks
  1. Nodestatus, roles, version, internal IP
  2. ConditionsReady=False/Unknown (kubelet down or network), MemoryPressure, DiskPressure, PIDPressure
  3. Taintscordoned or tainted nodes don't get new pods
  4. Allocated resourcesrequested vs allocatable CPU and memory
  5. Failing pods on the nodePending, Failed (often Evicted) pods scheduled there
  6. Node eventskubelet restarts, eviction thresholds, rebooted, NodeNotReady
  7. Usagelive CPU and memory of the node
  8. Versionskubelet, container runtime, OS image and kernel

My DevOps Playbook by Angelo John Calleja

New runbook

GitHub not connected

Saving is handled by the site: the GitHub token is stored in Cloudflare, not in your browser. Enter the editor password (the EDITOR_PASSWORD secret) to unlock saving in this browser.

Saving commits to gelogrammer/My_DevOps_Playbook. Create a fine-grained token with access to only this repo andContents: Read and write, then paste it here. It is stored only in this browser.

src/content/docs/…