PART 2: ADVANCED CONCEPTS
6. Output Formats
kubectl can output in many formats. Mastering these is the difference between "someone who uses kubectl" and "someone who is productive in kubectl."
The Formats
| Format | Flag | Use Case |
| Table | default | Human reading |
| Wide | -o wide | More columns |
| YAML | -o yaml | Full resource, editable |
| JSON | -o json | Machine parsing |
| Name | -o name | Just resource names |
| JSONPath | -o jsonpath='...' | Extract specific fields |
| Custom columns | -o custom-columns=... | Custom table |
| Go template | -o go-template='...' | Advanced templating |
YAML
bash
kubectl get pod nginx-abc123 -o yaml
kubectl get deployment web -o yaml > web-backup.yaml
Use for:
- Full resource inspection
- Backing up resources
- Understanding structure
JSON
bash
kubectl get pod nginx-abc123 -o json
kubectl get pod nginx-abc123 -o json | jq '.status.containerStatuses'
Use for:
- Scripting
- jq processing
- Integration with tools
Name
bash
kubectl get pods -o name
# pod/nginx-abc123
# pod/nginx-def456
# Use with other commands
kubectl get pods -o name | xargs kubectl delete
JSONPath
Extract specific fields:
bash
# Single field
kubectl get pod nginx-abc123 -o jsonpath='{.status.podIP}'
# Multiple fields
kubectl get pod nginx-abc123 -o jsonpath='{.metadata.name}{"\t"}{.status.podIP}{"\n"}'
# Loop over list
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# Loop with format
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
# Filter by field
kubectl get pods -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}'
# First item
kubectl get pod -o jsonpath='{.items[0].metadata.name}'
Common JSONPath patterns:
| Pattern | Purpose |
.metadata.name | Pod name |
.status.podIP | Pod IP |
.spec.nodeName | Node name |
.status.phase | Pod phase |
.spec.containers[*].image | All container images |
.metadata.labels | All labels |
.metadata.annotations['key'] | Specific annotation |
Custom Columns
Build your own tables:
bash
# Simple
kubectl get pods -o custom-columns=NAME:.metadata.name,IP:.status.podIP
# With headers
kubectl get pods -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,STATUS:.status.phase'
# Complex
kubectl get pods -o custom-columns='NAME:.metadata.name,IMAGE:.spec.containers[0].image,CPU:.spec.containers[0].resources.requests.cpu'
Use cases:
| Scenario | Custom Column |
| Capacity audit | NAME:.metadata.name,CPU:.spec.containers[0].resources.requests.cpu,MEM:.spec.containers[0].resources.requests.memory |
| Image audit | NAME:.metadata.name,IMAGE:.spec.containers[*].image |
| Node assignment | NAME:.metadata.name,NODE:.spec.nodeName |
| Missing limits | NAME:.metadata.name,LIMITS:.spec.containers[0].resources.limits |
Go Template
Full Go templating:
bash
kubectl get pods -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
Rarely used; JSONPath is more common.
jq Integration
For complex processing, JSON + jq is the standard:
bash
# Pods with their images
kubectl get pods -o json | jq '.items[] | {name: .metadata.name, image: .spec.containers[0].image}'
# Pods consuming > 500m CPU
kubectl get pods -o json | jq '.items[] | select(.spec.containers[0].resources.requests.cpu | rtrimstr("m") | tonumber > 500) | .metadata.name'
# Nodes with taints
kubectl get nodes -o json | jq '.items[] | select(.spec.taints != null) | {name: .metadata.name, taints: .spec.taints}'
The Utility Cheat Sheet
| Need | Command |
| All Pod names | kubectl get pods -o name |
| Pod IPs | kubectl get pods -o wide |
| Specific field | -o jsonpath='{.field}' |
| Custom table | -o custom-columns=... |
| Process with jq | -o json | jq ... |
| Full YAML | -o yaml |
7. Label Selectors and Field Selectors
Label Selectors
Filter by labels:
bash
# Equality
kubectl get pods -l app=nginx
kubectl get pods -l app=nginx,env=prod
# Set-based
kubectl get pods -l 'env in (prod,staging)'
kubectl get pods -l 'env notin (dev)'
kubectl get pods -l 'app=nginx,env!=dev'
kubectl get pods -l '!canary'
# Exists
kubectl get pods -l 'app'
# Multiple with comma = AND
kubectl get pods -l 'app=nginx,version=1.25'
Field Selectors
Filter by object fields (limited to certain fields):
bash
# Pod phase
kubectl get pods --field-selector status.phase=Running
kubectl get pods --field-selector status.phase!=Running
# Node
kubectl get pods --field-selector spec.nodeName=node-1
# Multiple
kubectl get pods --field-selector status.phase=Running,spec.nodeName=node-1
Supported fields vary by resource. For Pods:
| Field | Purpose |
metadata.name | Pod name |
metadata.namespace | Namespace |
spec.nodeName | Node name |
status.phase | Pending/Running/Succeeded/Failed |
status.podIP | Pod IP |
Combining Both
bash
# Both label and field selector
kubectl get pods -l app=nginx --field-selector status.phase=Running
The Powerful Use Cases
bash
# Delete all Failed Pods
kubectl delete pods --field-selector status.phase=Failed
# Get all Pods on a specific node
kubectl get pods -A --field-selector spec.nodeName=node-1
# Get all Pods with a specific label
kubectl get pods -A -l app=nginx
# Get all containers in a label group
kubectl get pods -l app=nginx -o jsonpath='{.items[*].spec.containers[*].image}'
8. kubectl patch
kubectl patch modifies specific fields without replacing the whole resource.
Three Patch Types
| Type | Flag | Format |
| Strategic merge | default | YAML fragment |
| JSON merge | --type=merge | JSON fragment |
| JSON patch | --type=json | RFC 6902 operations |
Strategic Merge Patch
Merges YAML, using resource-specific merge logic:
bash
kubectl patch deployment web -p '{"spec":{"replicas":5}}'
kubectl patch deployment web -p '
spec:
template:
spec:
containers:
- name: web
image: nginx:1.26-alpine
'
The strategic part: Merges arrays by key (e.g., name in containers), not by index.
JSON Merge Patch
Merges JSON, no resource-specific logic:
bash
kubectl patch deployment web --type=merge -p '{"spec":{"replicas":5}}'
Arrays are replaced, not merged.
JSON Patch
Precise operations (add, remove, replace, move, copy, test):
bash
# Replace replicas
kubectl patch deployment web --type=json -p='[{"op":"replace","path":"/spec/replicas","value":5}]'
# Add annotation
kubectl patch deployment web --type=json -p='[{"op":"add","path":"/metadata/annotations/new-anno","value":"value"}]'
# Remove label
kubectl patch deployment web --type=json -p='[{"op":"remove","path":"/metadata/labels/old-label"}]'
# Test then replace
kubectl patch deployment web --type=json -p='[
{"op":"test","path":"/spec/replicas","value":3},
{"op":"replace","path":"/spec/replicas","value":5}
]'
When to Use Patches
| Scenario | Patch Type |
| Simple field change | Strategic merge |
| Array element update | Strategic merge |
| Add/remove specific field | JSON patch |
| Conditional update | JSON patch with test |
| Atomic multi-field change | JSON patch |
The kubectl patch Advantage
Patches are:
- Smaller than full manifests
- Safer (only touch specific fields)
- Faster than
edit(no editor) - Scriptable
Common Patterns
bash
# Scale
kubectl patch deployment web -p '{"spec":{"replicas":5}}'
# Add annotation
kubectl patch deployment web -p '{"metadata":{"annotations":{"owner":"alice"}}}'
# Add label
kubectl patch deployment web -p '{"metadata":{"labels":{"env":"prod"}}}'
# Update image
kubectl patch deployment web -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","image":"nginx:1.26-alpine"}]}}}}'
# Add resource limits
kubectl patch deployment web -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","resources":{"limits":{"memory":"512Mi"}}}]}}}}'
# Remove finalizer
kubectl patch pod stuck-pod --type=json -p='[{"op":"remove","path":"/metadata/finalizers"}]'
9. kubectl edit, scale, set, rollout
kubectl edit
Opens the live resource in your editor. Changes are validated and applied on save.
bash
kubectl edit deployment web
kubectl edit svc nginx
kubectl edit configmap app-config
Pros: Fast for one-off changes.
Cons: Not reproducible, no review, easy to make mistakes.
Production tip: Never use edit in production. Use apply from a versioned manifest.
kubectl scale
Change replicas:
bash
kubectl scale deployment web --replicas=5
kubectl scale deployment web --replicas=0 # Scale to zero
kubectl scale statefulset db --replicas=3
kubectl scale deployment --all --replicas=3
kubectl scale deployment -l app=web --replicas=5
kubectl set
Update specific fields:
bash
# Image
kubectl set image deployment/web web=nginx:1.26-alpine
kubectl set image deployment/web web=nginx:1.26-alpine sidecar=busybox:1.36
# Resources
kubectl set resources deployment/web --limits=cpu=500m,memory=512Mi
kubectl set resources deployment/web --requests=cpu=100m,memory=128Mi
# Env vars
kubectl set env deployment/web LOG_LEVEL=debug
kubectl set env deployment/web --from=configmap/app-config
# ServiceAccount
kubectl set serviceaccount deployment/web app-sa
# Selector (rarely used)
kubectl set selector svc/web app=web
kubectl rollout
Manage Deployments, DaemonSets, StatefulSets:
bash
# Status
kubectl rollout status deployment/web
# History
kubectl rollout history deployment/web
kubectl rollout history deployment/web --revision=2
# Undo (rollback)
kubectl rollout undo deployment/web # Previous
kubectl rollout undo deployment/web --to-revision=1 # Specific
# Pause/Resume
kubectl rollout pause deployment/web
kubectl rollout resume deployment/web
# Restart (rolling restart)
kubectl rollout restart deployment/web
kubectl rollout restart statefulset/db
kubectl rollout restart daemonset/fluentd
The restart trick: kubectl rollout restart is the standard way to trigger a rolling restart without changing the image. Useful for picking up ConfigMap changes.
10. Events and Their Role in Debugging
Events are cluster-level notifications of what's happening. They're the single most underrated debugging tool.
Viewing Events
bash
# Current namespace
kubectl get events
# Sorted by time
kubectl get events --sort-by=.metadata.creationTimestamp
# Specific resource
kubectl get events --field-selector involvedObject.name=nginx-abc123
# Watch
kubectl get events -w
# All namespaces
kubectl get events -A
# Recent only
kubectl get events --field-selector type=Warning
# Since a time
kubectl get events --since=1h
In kubectl describe
Events appear at the bottom of describe:
bash
kubectl describe pod nginx-abc123
text
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 5m default-scheduler Successfully assigned default/nginx to node-1
Normal Pulling 5m kubelet Pulling image "nginx:1.25"
Normal Pulled 4m kubelet Successfully pulled image
Normal Created 4m kubelet Created container nginx
Normal Started 4m kubelet Started container nginx
Common Event Reasons
| Reason | Meaning |
| Scheduled | Pod assigned to node |
| Pulling | Pulling image |
| Pulled | Image pulled successfully |
| Failed | Image pull failed |
| BackOff | Retry backoff |
| Created | Container created |
| Started | Container started |
| Killing | Container being killed |
| Unhealthy | Probe failed |
| FailedScheduling | Can't schedule |
| Evicted | Pod evicted (node pressure) |
| FailedMount | Volume mount failed |
| FailedAttachVolume | Volume attach failed |
Event Retention
Events are ephemeral. By default, they last 1 hour in etcd. This means:
- If you don't look soon, they're gone
- Long-running incidents need external logging
- Tools like
kubectl-event-exporterpersist events to a backend
The Debugging Flow
text
1. kubectl get pods → spot the problem
2. kubectl describe pod → read Events
3. kubectl logs pod → read app logs
4. kubectl get events -A → cluster-wide context
11. kubectl debug and Ephemeral Containers
The killer feature for production debugging.
The Problem kubectl debug Solves
Traditional debugging:
kubectl execrequires the container to have a shell- Distroless images have no shell
- Starting a new Pod to debug requires network access, volume mounts, etc.
kubectl debug modes
Mode 1: Ephemeral container in a running Pod
bash
kubectl debug -it nginx-abc123 --image=busybox --target=nginx
This adds an ephemeral container to the Pod, sharing its network/process namespace. You can then:
ps auxto see processesnetstatto see connections- Read files via the shared mount namespace
Mode 2: Copy a Pod with modifications
bash
kubectl debug nginx-abc123 --copy-to=debug-pod --image=busybox
Creates a new Pod with the same spec but a different image.
Mode 3: Debug a Node
bash
kubectl debug node/node-1 -it --image=busybox
Creates a Pod on the node with host namespaces. Useful for node-level debugging.
Mode 4: Debug with a custom profile
bash
kubectl debug nginx-abc123 --profile=netadmin --image=nicolaka/netshoot
Profiles: legacy, general, baseline, netadmin, restricted, sysadmin.
Ephemeral Containers
Ephemeral containers are specifically designed for debugging. They:
- Can be added to running Pods
- Share the Pod's network/process namespace
- Have their own filesystem
- Cannot be removed (only Pod deletion removes them)
- Do not count against Pod resource limits
Example:
yaml
ephemeralContainers:
- name: debugger
image: busybox
command: ['sh']
targetContainerName: nginx
stdin: true
tty: true
Common Debug Images
| Image | Purpose |
| busybox | Small, has basic tools |
| nicolaka/netshoot | Network debugging (tcpdump, dig, curl) |
| alpine | Slightly larger, has more tools |
| ubuntu | Full Linux environment |
| koolkits/kubernetes | Kubernetes-focused |
| koolkits/java | Java-focused |
The Debug Workflow
bash
# 1. Pod is broken
kubectl get pods
# nginx-abc123 1/2 CrashLoopBackOff
# 2. Try to exec (may fail with distroless)
kubectl exec -it nginx-abc123 -- sh
# error: exec: "sh": executable file not found
# 3. Use kubectl debug
kubectl debug -it nginx-abc123 --image=busybox --target=nginx
# 4. Now you can inspect the container's process namespace
ps aux
cat /proc/1/cmdline
ls /proc/1/root/ # Container's root filesystem!
# 5. Clean up
kubectl delete pod nginx-abc123 # Or remove just the ephemeral container (not supported directly)
Security Considerations
| Risk | Mitigation |
| Ephemeral container escape | RBAC restrict pods/ephemeralcontainers |
| Privileged debugging | Avoid --profile=sysadmin unless needed |
| Data exposure | Debug containers can read Pod filesystem |
| Persistence | Ephemeral containers can't be removed individually |
RBAC for ephemeral containers:
yaml
- apiGroups: [""]
resources: ["pods/ephemeralcontainers"]
verbs: ["update"]
12. kubectl exec, port-forward, cp
kubectl exec
We covered exec basics in Part 1. Advanced patterns:
bash
# Redirect stdin
echo "hello" | kubectl exec -i nginx-abc123 -- cat
# Redirect stdout to file
kubectl exec nginx-abc123 -- cat /var/log/nginx/access.log > access.log
# No TTY (for scripts)
kubectl exec nginx-abc123 -- env
# Distroless (no shell, but binary exists)
kubectl exec nginx-abc123 -- /usr/bin/nginx -v
# Multiple containers
kubectl exec -it nginx-abc123 -c sidecar -- sh
The exec limitation: You can only exec into a container that has the binary you want. Distroless containers have no shell.
kubectl port-forward
Forwards a local port to a Pod or Service:
bash
# Pod
kubectl port-forward pod/nginx-abc123 8080:80
# Service
kubectl port-forward svc/nginx 8080:80
# Deployment
kubectl port-forward deployment/nginx 8080:80
# Specific local IP
kubectl port-forward --address=0.0.0.0 pod/nginx-abc123 8080:80
# Random local port
kubectl port-forward pod/nginx-abc123 :80
# Multiple ports
kubectl port-forward pod/nginx-abc123 8080:80 8443:443
# In the background
kubectl port-forward pod/nginx-abc123 8080:80 &
Limitations:
- Single connection at a time (actually multiple, but sequential)
- Not for production — use Ingress or LoadBalancer
- Can be slow — especially for high-throughput
Use cases:
- Accessing a database for debugging
- Testing a Service without exposing it
- Local development against a cluster
kubectl cp
Copies files between local and Pods:
bash
# Pod to local
kubectl cp nginx-abc123:/var/log/nginx/access.log ./access.log
# Local to Pod
kubectl cp ./config.yaml nginx-abc123:/etc/config/
# With namespace
kubectl cp -n prod nginx-abc123:/app/data.tar.gz ./data.tar.gz
# Specific container
kubectl cp -c sidecar nginx-abc123:/logs/ ./logs/
# Directory
kubectl cp nginx-abc123:/app/ ./app-backup/
# Symlink handling
kubectl cp --no-preserve nginx-abc123:/app/ ./app-backup/
Requirements:
tarmust be in the container- Fails on distroless images
Alternatives for distroless:
kubectl execwithcatand pipekubectl debugwith an ephemeral container that hastar- Copy from the node's filesystem
13. kubectl top, api-resources, explain, auth
kubectl top
Live resource usage:
bash
# Pods
kubectl top pods
kubectl top pods -A
kubectl top pods --sort-by=cpu
kubectl top pods --sort-by=memory
kubectl top pods -l app=nginx
# Containers
kubectl top pods --containers
# Nodes
kubectl top nodes
kubectl top nodes --sort-by=cpu
Requires metrics-server to be installed in the cluster.
Common issue: "error: Metrics API not available" — install metrics-server.
kubectl api-resources
Lists all resource types the cluster supports:
bash
kubectl api-resources
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false
kubectl api-resources --verbs=list,get
kubectl api-resources | grep -i deployment
Output:
text
NAME SHORTNAMES APIVERSION NAMESPACED KIND
pods po v1 true Pod
deployments deploy apps/v1 true Deployment
nodes no v1 false Node
Use for: Discovering what a cluster supports.
kubectl api-versions
Lists API versions:
bash
kubectl api-versions
# apps/v1
# batch/v1
# networking.k8s.io/v1
# ...
kubectl explain
Built-in documentation:
bash
# Resource
kubectl explain pod
kubectl explain deployment
kubectl explain service
# Field
kubectl explain pod.spec
kubectl explain pod.spec.containers
kubectl explain pod.spec.containers.resources
kubectl explain pod.spec.containers.resources.limits
# Recursive (all nested fields)
kubectl explain deployment --recursive
# Specific version
kubectl explain deployment.spec --api-version=apps/v1
The value: Never leave the terminal. Faster than browser.
kubectl auth can-i
Checks permissions:
bash
# Can I do X?
kubectl auth can-i create pods
kubectl auth can-i delete deployments
kubectl auth can-i get secrets -n prod
# As another user/SA
kubectl auth can-i list pods --as=system:serviceaccount:default:my-sa
kubectl auth can-i list pods --as=alice
# All permissions
kubectl auth can-i --list
kubectl auth can-i --list -n prod
# All namespaces
kubectl auth can-i list pods --all-namespaces
The debugging value: When something fails with "forbidden," use can-i to confirm what's allowed.
kubectl cluster-info
bash
kubectl cluster-info
# Kubernetes control plane is running at https://k8s.example.com:6443
# CoreDNS is running at https://...
kubectl cluster-info dump
# Dumps all cluster state for debugging
kubectl get --raw
Direct API access:
bash
# Get a resource via API path
kubectl get --raw /api/v1/namespaces/default/pods
kubectl get --raw /healthz
kubectl get --raw /metrics
# Pretty print
kubectl get --raw /api/v1/namespaces/default/pods | jq
14. kubectl Plugins
kubectl supports plugins: any executable named kubectl-<plugin> on the PATH becomes a subcommand.
How Plugins Work
If /usr/local/bin/kubectl-foo exists and is executable, then:
bash
kubectl foo # Runs kubectl-foo
krew (The Plugin Manager)
krew is the standard plugin manager:
bash
# Install krew
(
set -x; cd "$(mktemp -d)" &&
OS="$(uname | tr '[:upper:]' '[:lower:]')" &&
ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')" &&
KREW="krew-${OS}_${ARCH}" &&
curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/${KREW}.tar.gz" &&
tar zxvf "${KREW}.tar.gz" &&
./"${KREW}" install krew
)
# Add to PATH
export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"
# Search plugins
kubectl krew search
# Install
kubectl krew install ctx
kubectl krew install ns
kubectl krew install neat
kubectl krew install tree
kubectl krew install who-can
kubectl krew install outdated
kubectl krew install images
kubectl krew install resource-capacity
kubectl krew install tail
kubectl krew install view-secret
kubectl krew install cost
# List installed
kubectl krew list
# Upgrade
kubectl krew upgrade
# Uninstall
kubectl krew uninstall ctx
Essential Plugins
| Plugin | Purpose |
| kubectx (ctx) | Switch contexts fast |
| kubens (ns) | Switch namespaces fast |
| neat | Clean YAML output |
| tree | Resource hierarchy |
| who-can | Check permissions |
| outdated | Find outdated images |
| images | List images per workload |
| resource-capacity | Cluster capacity view |
| tail | Multi-Pod log tailing |
| view-secret | Decode Secrets |
| cost | Cost visibility |
| popeye | Cluster sanitizer |
| kubectl-ice | Per-Pod resource view |
| kubectl-kruise | Enhanced rolling updates |
| kubectl-node-shell | SSH into nodes via Pod |
Building a Plugin
A plugin is just a script:
bash
#!/usr/bin/env bash
# File: /usr/local/bin/kubectl-hello
echo "Hello from a kubectl plugin!"
echo "Args: $@"
bash
chmod +x /usr/local/bin/kubectl-hello
kubectl hello world
# Hello from a kubectl plugin!
# Args: world
Notable Third-Party Plugins (Not in krew)
| Tool | Purpose |
| k9s | Full-screen TUI for Kubernetes |
| kubectl-aliases | Shell aliases for common commands |
| kubie | Context-aware kubeconfig manager |
| kubespy | Live watch a resource type |
| stern | Multi-Pod log tailing (better than kubectl tail) |
| popeye | Cluster sanitizer |
| kubectl-neat | Clean up YAML output |
The kubectl Alias Cheat Sheet
Add to your ~/.bashrc or ~/.zshrc:
bash
alias k='kubectl'
alias kg='kubectl get'
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgd='kubectl get deployment'
alias kd='kubectl describe'
alias kdd='kubectl describe deployment'
alias kl='kubectl logs'
alias klf='kubectl logs -f'
alias ke='kubectl exec -it'
alias ka='kubectl apply -f'
alias kdel='kubectl delete'
alias kx='kubectx'
alias kn='kubens'
# Add completion
source <(kubectl completion bash)
complete -F __start_kubectl k
15. kubectl diff and Dry Runs
kubectl diff
Shows what would change if you applied a manifest:
bash
kubectl diff -f deployment.yaml
kubectl diff -f ./manifests/
kubectl diff -k ./kustomize/
Output: A unified diff (like git diff) of the changes.
Use case: Preview changes before applying. Essential for safe changes.
Dry Runs
Client-side dry run:
bash
kubectl apply -f deployment.yaml --dry-run=client
kubectl apply -f deployment.yaml --dry-run=client -o yaml
- Doesn't send to server
- Validates locally
- Useful for generating manifests from commands
Server-side dry run:
bash
kubectl apply -f deployment.yaml --dry-run=server
- Sends to server
- Full validation including admission webhooks
- Better for pre-apply validation
Use cases:
| Scenario | Dry Run Mode |
| Generate manifest from imperative | --dry-run=client -o yaml |
| Validate YAML syntax | --dry-run=client |
| Check admission webhooks | --dry-run=server |
| Preview changes | kubectl diff |
16. Common Failure Patterns
The 10 failure patterns you'll see most.
1. CrashLoopBackOff
Symptoms: Pod status shows CrashLoopBackOff, restart count is high.
Root causes:
- App crashes on startup
- Missing ConfigMap or Secret
- Bad command or arguments
- Missing dependencies
Debug:
bash
kubectl describe pod <pod> # Check Events
kubectl logs <pod> # Current logs
kubectl logs <pod> --previous # Previous instance logs
kubectl get pod <pod> -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}'
2. ImagePullBackOff / ErrImagePull
Symptoms: Pod status shows ImagePullBackOff.
Root causes:
- Wrong image name or tag
- Private registry without
imagePullSecrets - Registry unreachable
- Docker Hub rate limit
Debug:
bash
kubectl describe pod <pod> | grep -A5 Events
kubectl get secret <registry-secret> -o yaml
3. Pending
Symptoms: Pod stays in Pending phase.
Root causes:
- Insufficient resources on any node
- Node selector/affinity mismatch
- Taints without tolerations
- PVC not bound
- PodDisruptionBudget blocks eviction
Debug:
bash
kubectl describe pod <pod> # Check Events
kubectl get nodes # Resource availability
kubectl describe nodes | grep -A5 "Allocated resources"
kubectl get pvc # PVC status
4. OOMKilled
Symptoms: Exit code 137, restart, OOMKilled in container status.
Root causes:
- Memory limit too low
- Memory leak
- Traffic spike
Debug:
bash
kubectl describe pod <pod> | grep -i oom
kubectl top pod <pod>
kubectl get pod <pod> -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}'
5. Readiness Probe Failures
Symptoms: Pod status shows Running but 0/1 READY, so it's not in Service endpoints.
Root causes:
- Probe path wrong
- App slow to start
- Startup dependencies not ready
Debug:
bash
kubectl describe pod <pod> | grep -A3 "Readiness"
kubectl exec <pod> -- curl -v localhost:<port>/<path>
6. Service Has No Endpoints
Symptoms: kubectl get endpoints <svc> returns <none>.
Root causes:
- Service selector doesn't match Pod labels
- Pods not Ready
- Wrong port names
Debug:
bash
kubectl describe svc <svc>
kubectl get pods -l <selector-from-service>
kubectl get endpoints <svc>
7. CreateContainerConfigError
Symptoms: Container can't start, config error.
Root causes:
- Missing ConfigMap
- Missing Secret
- Missing key in ConfigMap/Secret
Debug:
bash
kubectl describe pod <pod> | grep -A5 Events
kubectl get configmap <name>
kubectl get secret <name>
8. FailedScheduling
Symptoms: Pod stays Pending, Events show FailedScheduling.
Root causes:
- No node has enough resources
- Taints/affinity prevent scheduling
- PVC unbound
Debug:
bash
kubectl describe pod <pod> | grep -A5 "FailedScheduling"
kubectl get nodes -o wide
kubectl describe node <node> | grep -A5 "Taints"
9. FailedMount
Symptoms: Pod stuck in ContainerCreating, Events show FailedMount.
Root causes:
- PVC not bound
- Volume attach failed
- Node can't reach storage
Debug:
bash
kubectl describe pod <pod> | grep -A10 "FailedMount"
kubectl get pvc
kubectl get pv
10. Node NotReady
Symptoms: Node status shows NotReady.
Root causes:
- kubelet down
- Disk pressure
- Network partition
- Certificate expired
Debug:
bash
kubectl describe node <node>
kubectl get events --field-selector involvedObject.name=<node>
# SSH to node, check kubelet
ssh <node>
systemctl status kubelet
journalctl -u kubelet -n 100
1:1 copy of the class Google Doc, code in code blocks.