Advertisementslot: not configuredSet AdSense publisher and slot env vars in .env.local

kubectl Cheat Sheet

The most complete kubectl command reference for daily use, interviews, and certification exams.


Setup & Productivity Aliases

# Essential aliases — add to ~/.zshrc or ~/.bashrc
alias k=kubectl
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgd='kubectl get deployment'
alias kgn='kubectl get nodes'
alias kdp='kubectl describe pod'

# Dry-run shorthand (use with -o yaml to generate manifests)
export do='--dry-run=client -o yaml'
export now='--grace-period=0 --force'

# Examples
k run nginx --image=nginx $do > pod.yaml
k delete pod stuck-pod $now

Cluster Info

kubectl version --short
kubectl cluster-info
kubectl get nodes -o wide
kubectl top nodes                          # requires metrics-server
kubectl get componentstatuses             # control plane health (deprecated in 1.19+)
kubectl config view
kubectl config get-contexts
kubectl config use-context <name>
kubectl config current-context

Namespace Operations

kubectl get namespaces
kubectl create namespace staging
kubectl delete namespace staging

# Set default namespace for current session
kubectl config set-context --current --namespace=staging

# List resources in ALL namespaces
kubectl get pods -A
kubectl get pods --all-namespaces

Pod Operations

# Create / run
kubectl run nginx --image=nginx:1.27
kubectl run busybox --image=busybox --rm -it -- /bin/sh    # interactive, auto-delete

# Get
kubectl get pods
kubectl get pods -o wide                  # show node, IP
kubectl get pods -w                       # watch (live updates)
kubectl get pods -l app=frontend          # filter by label
kubectl get pods --field-selector=status.phase=Running

# Describe
kubectl describe pod <name> -n <ns>       # events + full spec — most useful for debugging

# Logs
kubectl logs <pod>
kubectl logs <pod> -c <container>         # specific container in multi-container pod
kubectl logs <pod> --previous             # logs from crashed container
kubectl logs -f <pod>                     # follow/stream
kubectl logs -l app=api --all-containers  # aggregate logs by label

# Execute
kubectl exec -it <pod> -- /bin/sh
kubectl exec -it <pod> -c <container> -- bash

# Port forward
kubectl port-forward pod/<pod> 8080:80
kubectl port-forward svc/<service> 8080:80
kubectl port-forward deployment/<deploy> 8080:80

# Copy files
kubectl cp <pod>:/etc/config ./local-config
kubectl cp ./local-file <pod>:/tmp/file

# Delete
kubectl delete pod <name>
kubectl delete pod <name> --grace-period=0 --force    # immediate
kubectl delete pods -l app=old --force

# Top (requires metrics-server)
kubectl top pods
kubectl top pods --sort-by=cpu
kubectl top pods --sort-by=memory

Deployment Operations

# Create
kubectl create deployment web --image=nginx:1.27 --replicas=3
kubectl create deployment web --image=nginx $do > deploy.yaml

# Get / describe
kubectl get deployments
kubectl describe deployment <name>

# Scale
kubectl scale deployment web --replicas=10
kubectl autoscale deployment web --min=2 --max=20 --cpu-percent=70

# Update image (triggers rolling update)
kubectl set image deployment/web nginx=nginx:1.28
kubectl set resources deployment/web -c=nginx --limits=cpu=200m,memory=512Mi

# Rollout management
kubectl rollout status deployment/web
kubectl rollout history deployment/web
kubectl rollout history deployment/web --revision=3
kubectl rollout undo deployment/web
kubectl rollout undo deployment/web --to-revision=2
kubectl rollout pause deployment/web
kubectl rollout resume deployment/web

# Edit in place
kubectl edit deployment web

Service Operations

# Create
kubectl expose deployment web --port=80 --target-port=8080 --type=ClusterIP
kubectl expose deployment web --port=80 --type=NodePort
kubectl expose deployment web --port=80 --type=LoadBalancer

kubectl create service clusterip my-svc --tcp=80:8080
kubectl create service nodeport my-svc --tcp=80:8080

# Get
kubectl get svc
kubectl get svc -o wide
kubectl get endpoints <svc-name>         # see which pods are behind a service

# DNS test
kubectl run dns-test --image=busybox --rm -it -- nslookup my-svc.default.svc.cluster.local

ConfigMap & Secret Operations

# ConfigMap
kubectl create configmap app-config --from-literal=ENV=prod --from-literal=LOG=debug
kubectl create configmap app-config --from-file=config.properties
kubectl create configmap app-config --from-env-file=.env
kubectl get configmap app-config -o yaml
kubectl edit configmap app-config

# Secret
kubectl create secret generic db-creds \
  --from-literal=username=admin \
  --from-literal=password=s3cr3t
kubectl create secret docker-registry regcred \
  --docker-server=registry.example.com \
  --docker-username=user \
  --docker-password=pass
kubectl create secret tls tls-secret --cert=tls.crt --key=tls.key

# View secret values
kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -d
kubectl get secret db-creds -o json | jq -r '.data | map_values(@base64d)'

Storage Operations

kubectl get pv                            # PersistentVolumes (cluster-wide)
kubectl get pvc                           # PersistentVolumeClaims (namespaced)
kubectl get storageclass
kubectl describe pvc my-pvc              # check why PVC is stuck in Pending
kubectl delete pvc my-pvc               # WARNING: may delete data depending on reclaim policy

RBAC Operations

# Check permissions
kubectl auth can-i create pods
kubectl auth can-i list secrets -n kube-system
kubectl auth can-i '*' '*'               # am I cluster-admin?
kubectl auth can-i get pods --as=system:serviceaccount:staging:app-sa -n staging

# Create role & binding
kubectl create role pod-reader --verb=get,list,watch --resource=pods -n staging
kubectl create rolebinding pod-reader-binding \
  --role=pod-reader \
  --serviceaccount=staging:app-sa \
  -n staging

# ClusterRole
kubectl create clusterrole node-reader --verb=get,list,watch --resource=nodes
kubectl create clusterrolebinding node-reader-binding \
  --clusterrole=node-reader \
  --user=jane

# List who can do what
kubectl get rolebindings,clusterrolebindings -A | grep <subject>

Node Operations

kubectl get nodes
kubectl get nodes -o wide
kubectl describe node <node>
kubectl top node <node>

# Cordon — prevent new pods from scheduling on this node
kubectl cordon <node>
kubectl uncordon <node>

# Drain — evict all pods, then cordon
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data --force

# Label / taint
kubectl label node worker-1 disktype=ssd
kubectl label node worker-1 disktype-          # remove label

kubectl taint node gpu-node gpu=true:NoSchedule
kubectl taint node gpu-node gpu=true:NoSchedule-   # remove taint

Apply / Manage Manifests

kubectl apply -f manifest.yaml
kubectl apply -f ./manifests/             # all files in directory
kubectl apply -f https://url/manifest.yaml
kubectl apply -k overlays/production/     # Kustomize overlay

kubectl delete -f manifest.yaml
kubectl diff -f manifest.yaml             # see what would change before applying

# Dry run
kubectl apply -f manifest.yaml --dry-run=client
kubectl apply -f manifest.yaml --dry-run=server   # validates server-side

Debugging & Troubleshooting

# Ephemeral debug container (K8s 1.23+)
kubectl debug -it <pod> --image=busybox:latest --target=<container>

# Copy pod with different image for debugging
kubectl debug <pod> -it --copy-to=debug-pod --image=ubuntu --share-processes

# Get events (sorted by time)
kubectl get events --sort-by='.lastTimestamp' -n <ns>
kubectl get events --field-selector reason=BackOff -n <ns>

# Check API resources available
kubectl api-resources
kubectl api-versions

# Explain any field
kubectl explain pod.spec.containers.resources
kubectl explain deployment.spec.strategy.rollingUpdate

Output Formatting

# Common output flags
-o wide          # extra columns (node, IP)
-o yaml          # full YAML spec
-o json          # full JSON
-o name          # just resource/name
-o jsonpath      # extract specific fields

# JSONPath examples
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pod my-pod -o jsonpath='{.spec.containers[0].image}'
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'

# Custom columns
kubectl get pods -o custom-columns='NAME:.metadata.name,IMAGE:.spec.containers[0].image,STATUS:.status.phase'

# Sort
kubectl get pods --sort-by='.metadata.creationTimestamp'
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

Useful One-Liners

# Delete all pods in CrashLoopBackOff
kubectl get pods -A | grep CrashLoopBackOff | awk '{print "kubectl delete pod " $2 " -n " $1}' | bash

# Force delete all Terminating pods
kubectl get pods -A | grep Terminating | awk '{print "kubectl delete pod " $2 " -n " $1 " --grace-period=0 --force"}' | bash

# List all images running in the cluster
kubectl get pods -A -o jsonpath='{range .items[*]}{.spec.containers[*].image}{"\n"}{end}' | sort -u

# List all resource requests/limits
kubectl get pods -A -o json | jq '.items[] | {name: .metadata.name, ns: .metadata.namespace, cpu_req: .spec.containers[].resources.requests.cpu, mem_req: .spec.containers[].resources.requests.memory}'

# Watch pod restarts live
watch -n2 'kubectl get pods -A --sort-by=".status.containerStatuses[0].restartCount" | tail -20'

# Get all non-running pods
kubectl get pods -A --field-selector=status.phase!=Running

# Check which pods are on a specific node
kubectl get pods -A -o wide --field-selector spec.nodeName=<node-name>

# Restart a deployment (rolling restart)
kubectl rollout restart deployment/<name> -n <ns>
Advertisementslot: not configuredSet AdSense publisher and slot env vars in .env.local
Use the sidebar to navigate between topics.