Loading...
The most complete practical kubectl reference for daily operations, interviews, and certification prep.
Looking for cheat sheets on Docker, Terraform, AWS, Linux, Kafka, and more? See the full Command Cheat Sheets index.
# 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'
# Useful shorthand flags
export do='--dry-run=client -o yaml'
export now='--grace-period=0 --force'
# Examples
k run nginx --image=nginx:1.27 $do > pod.yaml
k delete pod stuck-pod $now
kubectl version --short
kubectl cluster-info
kubectl get nodes -o wide
kubectl top nodes # requires metrics-server
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
kubectl config set-context --current --namespace=staging
kubectl get pods -A
kubectl get all -n staging
# Create / run
kubectl run nginx --image=nginx:1.27
kubectl run busybox --image=busybox --rm -it -- /bin/sh
# List and inspect
kubectl get pods
kubectl get pods -o wide
kubectl get pods -w
kubectl get pods -l app=frontend
kubectl get pods --field-selector=status.phase=Running
kubectl describe pod <name> -n <ns>
# Logs and debugging
kubectl logs <pod>
kubectl logs <pod> -c <container>
kubectl logs <pod> --previous
kubectl logs -f <pod>
kubectl logs -l app=api --all-containers
# Execute and copy
kubectl exec -it <pod> -- /bin/sh
kubectl exec -it <pod> -c <container> -- bash
kubectl cp <pod>:/etc/config ./local-config
kubectl cp ./local-file <pod>:/tmp/file
# Delete and recover quickly
kubectl delete pod <name>
kubectl delete pod <name> --grace-period=0 --force
kubectl delete pods -l app=old --force
# Resource usage (requires metrics-server)
kubectl top pods
kubectl top pods --sort-by=cpu
kubectl top pods --sort-by=memory
# Create and inspect
ekubectl create deployment web --image=nginx:1.27 --replicas=3
kubectl get deployments
kubectl describe deployment <name>
# Scale and autoscale
kubectl scale deployment web --replicas=10
kubectl autoscale deployment web --min=2 --max=20 --cpu-percent=70
# Rolling updates
kubectl set image deployment/web nginx=nginx:1.28
kubectl set resources deployment/web -c=nginx --limits=cpu=200m,memory=512Mi
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 manifests directly
kubectl edit deployment web
# Service creation
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
# Inspect service routing
kubectl get svc
kubectl get svc -o wide
kubectl get endpoints <svc-name>
kubectl describe svc <svc-name>
# Port-forward for local debugging
kubectl port-forward pod/<pod> 8080:80
kubectl port-forward svc/<service> 8080:80
kubectl port-forward deployment/<deploy> 8080:80
# DNS sanity check
kubectl run dns-test --image=busybox:1.36 --rm -it -- nslookup my-svc.default.svc.cluster.local
# 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
# Inspect secret contents safely
kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -d
kubectl get secret db-creds -o json | jq -r '.data | map_values(@base64d)'
kubectl get pv
kubectl get pvc
kubectl get storageclass
kubectl describe pvc my-pvc
kubectl describe pv <pv-name>
# Common issue: PVC stuck in Pending
kubectl get events --sort-by=.lastTimestamp | grep -i pending
# Label resources
kubectl label deployment web tier=backend
kubectl label pod my-pod app=payments --overwrite
# List by labels
kubectl get pods -l app=payments
kubectl get pods -l 'app in (payments,auth)'
# Remove labels
kubectl label deployment web tier-
# Annotate for rollout or tooling
kubectl annotate deployment web owner=platform-team
kubectl create job welcome --image=busybox -- echo hello
kubectl get jobs
kubectl describe job <job-name>
kubectl logs job/<job-name>
kubectl create cronjob backup --schedule='0 * * * *' \
--image=busybox -- /bin/sh -c 'echo backup'
kubectl get cronjobs
kubectl describe cronjob <name>
# Example resource settings
kubectl set resources deployment/web -c=nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi
# Readiness and liveness probes
kubectl describe pod <pod> | grep -A10 -i 'readiness\|liveness'
# Check resource pressure
kubectl top pods
kubectl top nodes
kubectl describe node <node>
# Check what you can do
kubectl auth can-i create pods
kubectl auth can-i list secrets -n kube-system
kubectl auth can-i '*' '*'
kubectl auth can-i get pods --as=system:serviceaccount:staging:app-sa -n staging
# Role and binding examples
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
kubectl create clusterrole node-reader --verb=get,list,watch --resource=nodes
kubectl create clusterrolebinding node-reader-binding \
--clusterrole=node-reader \
--user=jane
# Find recent cluster issues
kubectl get events --sort-by=.lastTimestamp
kubectl get events -A --field-selector=type=Warning
# Diagnose pending pods
kubectl get pods -A | grep Pending
kubectl describe pod <pending-pod>
# Check node pressure and taints
kubectl describe node <node>
kubectl taint nodes <node> key=value:NoSchedule
kubectl cordon <node>
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data
# Show what changed in a rollout
kubectl rollout history deployment/<name>
# Find the pod behind a service
kubectl get endpoints <svc-name>
# Explain a failure quickly
kubectl describe pod <pod>
# Check whether a config change is live
kubectl get configmap <name> -o yaml
# Verify if the app is actually reachable
kubectl port-forward svc/<service> 8080:80
get tells you what exists.describe tells you why it is failing.logs tells you what the process is saying.exec lets you inspect the running container directly.rollout helps you manage safe deployments.events often reveal the real root cause before the app logs do.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
# 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
# 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'
# 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>
Learned the concepts? Test yourself with Kubernetes interview questions.
Go to the question bank →