Kubernetes Cheat Sheet
Quick reference for kubectl commands, Kubernetes resource types, debugging, and common YAML patterns.
Deep dive: Kubernetes Section | K8s Production Checklist | Power user: kubectl Advanced
kubectl Basics
Context & Config
| Command | Description |
|---|---|
kubectl config get-contexts | List all contexts |
kubectl config current-context | Show current context |
kubectl config use-context ctx | Switch context |
kubectl config set-context --current --namespace=ns | Set default namespace |
kubectl cluster-info | Cluster endpoint info |
kubectl api-resources | List all resource types |
kubectl api-versions | List API versions |
kubectl version | Client and server versions (keep kubectl within one minor of the server) |
kubectl explain pod.spec.containers | Built-in field docs for any resource |
kubectl auth whoami | Show the identity the API server sees |
Get Resources
| Command | Description |
|---|---|
kubectl get pods | List pods in current namespace |
kubectl get pods -A | List pods in all namespaces |
kubectl get pods -o wide | Pods with node and IP info |
kubectl get pods -o yaml | Full YAML output |
kubectl get pods -l app=web | Filter by label |
kubectl get pods --field-selector status.phase=Running | Filter by field |
kubectl get pods --sort-by=.metadata.creationTimestamp | Sort by creation time |
kubectl get all | Common workload resources in namespace (not ConfigMaps, Secrets, Ingresses, PVCs) |
kubectl get events --sort-by=.lastTimestamp | Events sorted by time (lastTimestamp can be empty for newer events) |
kubectl events | Events sorted by time (GA since 1.28; preferred) |
kubectl events --for pod/pod-name | Events for one object |
kubectl get pods -w | Watch for changes |
Create & Apply
| Command | Description |
|---|---|
kubectl apply -f manifest.yaml | Create or update from file |
kubectl apply -f ./dir/ | Apply all files in directory |
kubectl apply -k ./kustomize/ | Apply with Kustomize |
kubectl create ns my-namespace | Create namespace |
kubectl create secret generic s --from-literal=k=v | Create secret from literal |
kubectl create secret generic s --from-file=./key.pem | Create secret from file |
kubectl create configmap cm --from-literal=k=v | Create configmap |
kubectl create secret tls app-tls --cert=tls.crt --key=tls.key | Create TLS secret |
kubectl create secret docker-registry regcred --docker-server=ghcr.io --docker-username=u --docker-password=TOKEN | Image pull secret |
kubectl diff -f manifest.yaml | Show what apply would change |
kubectl apply --server-side -f manifest.yaml | Server-side apply (field ownership tracked by the API server) |
kubectl create deploy web --image=nginx:1.27 --dry-run=client -o yaml | Generate a YAML skeleton |
Edit & Delete
| Command | Description |
|---|---|
kubectl edit deployment app | Edit resource in editor |
kubectl delete -f manifest.yaml | Delete from file |
kubectl delete pod pod-name | Delete specific pod |
kubectl delete pods -l app=web | Delete pods by label |
kubectl delete ns my-namespace | Delete namespace and everything in it |
kubectl delete -f manifest.yaml -i | Interactive delete: list and confirm first |
kubectl label pod pod-name env=prod --overwrite | Add or change a label |
Describe & Logs
| Command | Description |
|---|---|
kubectl describe pod pod-name | Detailed pod info with events |
kubectl describe node node-name | Node capacity and allocations |
kubectl logs pod-name | Pod logs |
kubectl logs pod-name -c container | Specific container logs |
kubectl logs pod-name --previous | Previous container logs (after crash) |
kubectl logs -f pod-name | Follow logs |
kubectl logs -l app=web --all-containers | Logs from all pods with label (last 10 lines each, max 5 pods) |
kubectl logs deploy/app --since=1h --tail=200 | Logs from one pod of a deployment, time/line limited |
Exec & Port-Forward
| Command | Description |
|---|---|
kubectl exec -it pod-name -- sh | Shell into pod |
kubectl exec pod-name -- cmd | Run command in pod |
kubectl port-forward pod-name 8080:3000 | Forward local port to pod |
kubectl port-forward svc/service 8080:80 | Forward local port to service |
kubectl cp pod-name:/path ./local | Copy from pod (needs tar in the container) |
kubectl debug -it pod-name --image=busybox --target=app | Ephemeral debug container (for distroless images) |
Scaling & Rollouts
| Command | Description |
|---|---|
kubectl scale deployment app --replicas=5 | Scale deployment |
kubectl autoscale deployment app --min=2 --max=10 --cpu=80% | Create HPA (--cpu replaces the older --cpu-percent) |
kubectl rollout status deployment app | Watch rollout progress |
kubectl rollout history deployment app | Rollout history |
kubectl rollout undo deployment app | Rollback to previous |
kubectl rollout undo deployment app --to-revision=2 | Rollback to specific revision |
kubectl rollout restart deployment app | Rolling restart |
kubectl rollout pause deployment app / resume | Batch several changes into one rollout |
kubectl set image deployment app app=app:1.1.0 | Update image (starts a rollout) |
kubectl drain node --ignore-daemonsets --delete-emptydir-data | Evict pods before node maintenance |
kubectl cordon node / uncordon node | Stop / resume scheduling on a node |
Resource Types Quick Reference
| Resource | Short | Purpose |
|---|---|---|
| Pod | po | Smallest deployable unit |
| Deployment | deploy | Declarative pod management with rollouts |
| StatefulSet | sts | Stateful workloads with stable identity |
| DaemonSet | ds | One pod per node |
| Job | job | Run to completion |
| CronJob | cj | Scheduled jobs |
| Service | svc | Network endpoint for pods |
| Ingress | ing | HTTP routing and TLS termination |
| ConfigMap | cm | Non-sensitive configuration |
| Secret | secret | Sensitive configuration |
| PersistentVolumeClaim | pvc | Storage request |
| Namespace | ns | Resource isolation |
| ServiceAccount | sa | Pod identity |
| Role | role | Namespace-scoped permissions |
| ClusterRole | clusterrole | Cluster-scoped permissions |
| NetworkPolicy | netpol | Network traffic rules |
| HorizontalPodAutoscaler | hpa | Auto-scale by metrics |
| ReplicaSet | rs | Keeps N pod replicas (managed by Deployments) |
| PersistentVolume | pv | Cluster-wide storage volume |
| StorageClass | sc | Dynamic volume provisioning profile |
| PodDisruptionBudget | pdb | Limit voluntary evictions (drains, upgrades) |
| EndpointSlice | (none) | Pod IPs behind a Service (replaces deprecated Endpoints) |
| Gateway / HTTPRoute | gtw / (none) | Gateway API: successor to Ingress for L4/L7 routing |
| CustomResourceDefinition | crd | Extends the API with new types |
| Node | no | Worker machine |
Removed or deprecated APIs you may still see in old YAML
extensions/v1beta1andapps/v1beta1/v1beta2for Deployments, DaemonSets, ReplicaSets: removed in 1.16. Useapps/v1.extensions/v1beta1/networking.k8s.io/v1beta1Ingress: removed in 1.22. Usenetworking.k8s.io/v1.batch/v1beta1CronJob: removed in 1.25. Usebatch/v1.autoscaling/v2beta1/v2beta2HPA: removed in 1.25/1.26. Useautoscaling/v2.- PodSecurityPolicy (
policy/v1beta1): removed in 1.25. Use Pod Security Admission namespace labels (below) or a policy engine (Kyverno, OPA Gatekeeper, ValidatingAdmissionPolicy). - dockershim: removed in 1.24. Nodes run containerd or CRI-O; Docker-built images still work.
- v1 Endpoints: deprecated in 1.33. Use EndpointSlices.
Find them with kubectl convert (plugin) or a scanner such as pluto / kubent.
Common YAML Templates
Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: app
labels:
app: app
spec:
replicas: 3
selector:
matchLabels:
app: app
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
metadata:
labels:
app: app
spec:
containers:
- name: app
image: app:1.0.0
ports:
- containerPort: 3000
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
readinessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 15
periodSeconds: 20
# Optional: holds off liveness/readiness until slow startup finishes
startupProbe:
httpGet:
path: /health
port: 3000
failureThreshold: 30
periodSeconds: 5
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
seccompProfile:
type: RuntimeDefault
Native Sidecar Container (GA in 1.33)
spec:
initContainers:
- name: log-shipper
image: fluent/fluent-bit:3.2
restartPolicy: Always # makes it a sidecar: starts before, stops after the app
containers:
- name: app
image: app:1.0.0
Sidecars started this way do not block Job completion and are stopped after the main containers exit.
Pod Security Admission (replaces PodSecurityPolicy)
apiVersion: v1
kind: Namespace
metadata:
name: app
labels:
pod-security.kubernetes.io/enforce: restricted # privileged | baseline | restricted
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/audit: restricted
PodDisruptionBudget
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: app
spec:
minAvailable: 2 # or maxUnavailable: 1
selector:
matchLabels:
app: app
Service
apiVersion: v1
kind: Service
metadata:
name: app
spec:
selector:
app: app
ports:
- port: 80
targetPort: 3000
type: ClusterIP
Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: app
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
ingressClassName: nginx
tls:
- hosts:
- app.example.com
secretName: app-tls
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: app
port:
number: 80
ingress-nginx is retired
The community ingress-nginx controller (the one the nginx.ingress.kubernetes.io/* annotations above belong to) was retired by Kubernetes SIG Network, with best-effort maintenance ending in March 2026: no further releases or security fixes. The Ingress API itself is still GA but frozen. For new work use the Gateway API (below) or another maintained Ingress controller; annotations are controller-specific and do not carry over.
Gateway API (HTTPRoute)
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: web
spec:
gatewayClassName: my-gateway-class # provided by your controller (Envoy Gateway, Istio, Cilium, cloud LB...)
listeners:
- name: https
protocol: HTTPS
port: 443
hostname: app.example.com
tls:
certificateRefs:
- name: app-tls
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: app
spec:
parentRefs:
- name: web
hostnames: ["app.example.com"]
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: app
port: 80
Gateway API CRDs are not installed by default: kubectl get crd gateways.gateway.networking.k8s.io to check.
CronJob
apiVersion: batch/v1
kind: CronJob
metadata:
name: cleanup
spec:
schedule: "0 2 * * *"
timeZone: "Etc/UTC" # GA since 1.27; default is the controller's local time zone
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: cleanup
image: app:1.0.0
command: ["node", "scripts/cleanup.js"]
HPA
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: app
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: app
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
behavior:
scaleDown:
stabilizationWindowSeconds: 300
NetworkPolicy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: app-policy
spec:
podSelector:
matchLabels:
app: app
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- port: 3000
egress:
- to:
- podSelector:
matchLabels:
app: database
ports:
- port: 5432
Debugging Pods
Pod Status Meanings
| Status | Meaning | Action |
|---|---|---|
Pending | Waiting for scheduling | Check node resources, taints, PVC binding |
ContainerCreating | Pulling image or mounting volumes | Check image name, pull secrets, PVC |
Running | All containers started | Check readiness probe if not receiving traffic |
CrashLoopBackOff | Container crashing repeatedly | Check logs: kubectl logs pod --previous |
ImagePullBackOff | Cannot pull image | Check image name, registry credentials |
OOMKilled | Container exceeded its memory limit (a termination reason, shown in STATUS) | Increase memory limit or fix the leak |
CreateContainerConfigError | Referenced ConfigMap/Secret/key missing | kubectl describe pod, check names and keys |
Init:0/1, Init:CrashLoopBackOff | Init container not finished / failing | kubectl logs pod -c init-name |
Completed | Container exited 0 | Normal for Jobs; for Deployments the process should not exit |
Evicted | Node under resource pressure | Check node resources, set resource requests |
Terminating | Being deleted | Check finalizers if stuck |
Debug Flowchart
Pod not running?
|
+-- Status: Pending
| +-- kubectl describe pod -> check Events
| +-- No nodes available? Check resources, taints, affinity
| +-- PVC pending? Check StorageClass, PV availability
|
+-- Status: CrashLoopBackOff
| +-- kubectl logs pod --previous
| +-- Exit code 1? Application error
| +-- Exit code 137? SIGKILL - usually OOMKilled (check lastState.terminated.reason)
| +-- Exit code 143? SIGTERM - killed by liveness probe or shutdown
| +-- Exit code 0? Check restartPolicy
|
+-- Status: ImagePullBackOff
+-- Image name correct?
+-- Tag exists in registry?
+-- imagePullSecrets configured?
Debugging Commands
# Check why pod is pending
kubectl describe pod pod-name | grep -A 20 Events
# Check node resources
kubectl describe node node-name | grep -A 5 "Allocated resources"
# DNS debugging
kubectl run debug --image=busybox --rm -it --restart=Never -- nslookup service-name
# Network debugging
kubectl run debug --image=nicolaka/netshoot --rm -it --restart=Never -- bash
# Check if endpoint exists (v1 Endpoints, deprecated since 1.33)
kubectl get endpoints service-name
# Same via EndpointSlices (current API). Empty = selector matches no ready pods
kubectl get endpointslices -l kubernetes.io/service-name=service-name
# Events for a pod, newest last
kubectl events --for pod/pod-name
# Why was the last container killed?
kubectl get pod pod-name -o jsonpath='{.status.containerStatuses[*].lastState.terminated}'
# Check resource usage
kubectl top pods
kubectl top nodes
Resource Requests & Limits
Guidelines
| Resource | Request | Limit |
|---|---|---|
| CPU | Set to average usage | 2-5x request or no limit |
| Memory | Set to working set size | 1.5-2x request (many teams set limit = request to avoid OOM kills under node pressure) |
CPU over the limit is throttled; memory over the limit is OOM-killed. QoS class: Guaranteed (requests = limits for every container), Burstable (some requests), BestEffort (none, evicted first). Check with kubectl get pod p -o jsonpath='{.status.qosClass}'.
CPU Units
| Value | Meaning |
|---|---|
1 | 1 vCPU core |
500m | 0.5 vCPU core |
100m | 0.1 vCPU core |
Memory Units
| Value | Meaning |
|---|---|
128Mi | 128 mebibytes |
1Gi | 1 gibibyte |
512M | 512 megabytes (base 10) |
Service Types
| Type | Access | Use Case |
|---|---|---|
ClusterIP | Internal only | Service-to-service communication |
NodePort | External via node IP:port | Development, simple access |
LoadBalancer | External via cloud LB | Production external services |
ExternalName | DNS CNAME alias | Access external services |
Headless (clusterIP: None) | DNS returns pod IPs directly | StatefulSets, client-side load balancing |
In-cluster DNS name: service.namespace.svc.cluster.local (pods: pod-name.service.namespace.svc.cluster.local for StatefulSets).
Label Selectors
# Equality-based
kubectl get pods -l app=web
kubectl get pods -l app=web,tier=frontend
kubectl get pods -l 'app!=web'
# Set-based
kubectl get pods -l 'app in (web, api)'
kubectl get pods -l 'app notin (db)'
kubectl get pods -l 'tier'
kubectl get pods -l '!tier'
When to Use X vs Y
| Decision | Choice A | Choice B | Use A When | Use B When |
|---|---|---|---|---|
| Workload | Deployment | StatefulSet | Stateless apps | Databases, need stable identity |
| Workload | Deployment | DaemonSet | N replicas on scheduler's choice | One pod per node (agents, logs) |
| Config | ConfigMap | Secret | Non-sensitive configuration | Passwords, keys, tokens |
| Service | ClusterIP | LoadBalancer | Internal communication | External traffic |
| Scaling | HPA | VPA | Scale horizontally (add pods) | Scale vertically (bigger pods) |
| Networking | Ingress | Service LoadBalancer | HTTP routing, multiple hosts | TCP/UDP, single service |
| L7 routing | Gateway API | Ingress | New setups, header/weight routing, role separation | Existing setups on a maintained Ingress controller |
| Probes | readiness | liveness | Gate traffic until ready | Restart a hung process (keep it cheap and dependency-free) |
| Package | Helm | Kustomize | Complex apps, conditional logic | Overlays, patch-based config |
Useful Aliases
alias k='kubectl'
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgd='kubectl get deployments'
alias kgi='kubectl get ingress'
alias kga='kubectl get all'
alias kdp='kubectl describe pod'
alias kl='kubectl logs'
alias klf='kubectl logs -f'
alias ke='kubectl exec -it'
alias kaf='kubectl apply -f'
alias kdf='kubectl delete -f'
alias kctx='kubectl config use-context'
alias kns='kubectl config set-context --current --namespace'
Test Yourself
-
What command sets the default namespace for your current context?
kubectl config set-context --current --namespace=ns -
How do you get pods from all namespaces?
kubectl get pods -A -
What command shows detailed information and recent events for a pod?
kubectl describe pod pod-name -
How do you view the logs of a crashed container's previous run?
kubectl logs pod-name --previous -
What command rolls back a deployment to the previous revision?
kubectl rollout undo deployment app -
How do you forward local port 8080 to a service's port 80?
kubectl port-forward svc/service 8080:80 -
What is the short name for HorizontalPodAutoscaler in kubectl?
hpa -
What pod status means the container keeps crashing and restarting?
CrashLoopBackOff -
How do you apply all YAML files in a directory?
kubectl apply -f ./dir/ -
What command creates a secret from a literal key-value pair?
kubectl create secret generic s --from-literal=k=v
Common Gotchas
- Not setting resource requests and limits. Pods without requests can be scheduled on an overcommitted node and get OOMKilled. Always set both.
kubectl delete nsdeletes everything in that namespace. There is no confirmation prompt by default and no undo. Triple-check, or usekubectl delete ns x -i(interactive).- Forgetting readiness probes. Without them, traffic is sent to pods before the app is ready, causing 502 errors during deployments.
- Using
latestimage tag in Kubernetes. TheimagePullPolicydefaults toAlwaysforlatest, causing unexpected image pulls and non-reproducible deployments. Pin versions. - Ignoring
CrashLoopBackOffexit codes. Exit code 137 means the container got SIGKILL, most often OOMKilled (confirm withlastState.terminated.reason, then increase the memory limit); exit code 1 means application error (checkkubectl logs --previous). - Liveness probes that check dependencies. If
/healthcalls the database, a DB blip restarts every pod at once. Liveness should only check the process itself. - Changing a ConfigMap does not restart pods. Env vars are read at start; mounted files update after a delay (never for
subPathmounts). Runkubectl rollout restartor hash the config into a pod annotation. - Copying old manifests.
extensions/v1beta1, PodSecurityPolicy andbatch/v1beta1are gone;kubectl applyfails with "no matches for kind".
One-Liner Summary
Kubernetes is a container orchestrator that automates deployment, scaling, and self-healing -- master kubectl describe, logs --previous, and resource requests/limits to debug 90% of production issues.