Complete kubectl reference - context switching, pods, rollouts, patching, troubleshooting, output formatting, and RBAC for production clusters.
Verify which cluster you are targeting before running any command — the most common production incident starts here.
kubectl config get-contexts ## list all known contexts
kubectl config current-context ## show active context
kubectl config use-context prod-eks ## switch to prod
kubectl cluster-info ## control plane + DNS endpoint
kubectl version ## client and server versions
kubectl config view ## show merged kubeconfig
kubectl config view --raw ## include certs and secrets
Parameter Breakdown:
use-context: Switches the active cluster for all subsequent commandscurrent-context: Run this before any destructive command on shared clustersview --raw: Exposes embedded certificate data — handle output carefullySet this up once per machine — it pays for itself within a day.
## Bash
source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> ~/.bashrc
## Zsh
source <(kubectl completion zsh)
echo "source <(kubectl completion zsh)" >> ~/.zshrc
## Fish (kubectl 1.23+)
kubectl completion fish | source
Parameter Breakdown:
completion bash|zsh|fish: Generates the shell-specific completion scriptalias k=kubectl: Pair with complete -o default -F __start_kubectl k to autocomplete the alias tooThe commands you will run more than any others — listing, filtering, and inspecting live state.
kubectl get pods -n payments ## pods in a namespace
kubectl get pods -A ## all namespaces (-A = --all-namespaces)
kubectl get pods -o wide ## with node and IP columns
kubectl get pods -l app=orders-api ## filter by label
kubectl get pods --field-selector=status.phase=Running
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
kubectl describe pod orders-api-7d4b -n payments
kubectl get pod orders-api-7d4b -o yaml ## full resource definition
Command Parameter Table:
| Flag | Description |
|---|---|
-n |
Target a single namespace |
-A |
Search across every namespace |
-l |
Filter by label selector, e.g. app=orders-api |
Get inside a running or crashed container fast.
kubectl logs orders-api-7d4b -n payments ## current logs
kubectl logs orders-api-7d4b -f ## stream live
kubectl logs orders-api-7d4b --previous ## crashed container
kubectl logs orders-api-7d4b -c sidecar ## specific container
kubectl exec -it orders-api-7d4b -- bash ## interactive shell
kubectl debug orders-api-7d4b -it \
--image=busybox:1.28 ## attach a debug container
kubectl top pod orders-api-7d4b --containers ## live CPU/memory
Parameter Breakdown:
--previous: Logs from the last crashed instance of the containerdebug: Creates a sidecar debug container without restarting the pod — use when the image has no shelltop pod --containers: Breaks usage down per container, not just per podValidate before you mutate cluster state.
kubectl apply -f deployment.yaml
kubectl apply -f ./k8s/ ## apply a whole directory
kubectl diff -f deployment.yaml ## preview changes vs live state
kubectl apply -f deployment.yaml \
--dry-run=client ## local validation only
kubectl apply -f deployment.yaml \
--dry-run=server ## full admission validation
kubectl create deployment orders-api \
--image=razorpay/orders-api:v2.3.1 \
--dry-run=client -o yaml > deploy.yaml ## generate a manifest
Parameter Breakdown:
diff: Shows exactly what apply would change — run this before every production apply--dry-run=server: Runs real admission webhooks without persisting the change--dry-run=client -o yaml: Scaffolds a starting manifest instead of writing YAML by handShip and roll back deployments safely.
kubectl set image deployment/orders-api \
api=razorpay/orders-api:v2.3.1 -n payments
kubectl rollout status deployment/orders-api
kubectl rollout history deployment/orders-api
kubectl rollout undo deployment/orders-api
kubectl rollout undo deployment/orders-api \
--to-revision=3
kubectl rollout restart deployment/orders-api
kubectl scale deployment orders-api \
--replicas=5 -n payments
kubectl autoscale deployment orders-api \
--min=2 --max=10 --cpu-percent=70
Parameter Breakdown:
rollout restart: Forces a fresh rolling restart with no config change — useful to pick up a Secret/ConfigMap update--to-revision: Roll back to a specific point in history, not just the previous oneautoscale: Creates an HPA bound to CPU utilizationTargeted edits without opening a full YAML file.
kubectl patch deployment orders-api \
--subresource='scale' --type='merge' \
-p '{"spec":{"replicas":4}}'
kubectl patch pod orders-api-7d4b --type='json' \
-p='[{"op":"replace","path":"/spec/containers/0/image","value":"razorpay/orders-api:v2.3.2"}]'
kubectl label pods orders-api-7d4b tier=backend
kubectl label pods orders-api-7d4b tier- ## remove a label
kubectl annotate pods orders-api-7d4b \
owner=platform-team
Command Parameter Table:
| Flag | Description |
|---|---|
--type=merge |
Standard strategic merge patch |
--type=json |
RFC 6902 JSON patch — required for array index edits |
label key- |
Trailing dash removes that label |
Expose workloads and debug connectivity locally.
kubectl get svc -n payments
kubectl expose deployment orders-api \
--port=80 --target-port=8080 \
--type=ClusterIP -n payments
kubectl port-forward svc/orders-api 8080:80 -n payments
kubectl run curl-test --image=curlimages/curl \
-it --rm --restart=Never -- \
curl http://orders-api.payments.svc.cluster.local/health
Parameter Breakdown:
port-forward: Tunnels local traffic to a pod or service — for debugging only, never production traffic--type: ClusterIP (internal), NodePort (node IP), LoadBalancer (cloud LB)--rm: Deletes the throwaway test pod immediately after the command exitsRead and manage configuration without leaking values into shell history.
kubectl create configmap app-config \
--from-literal=DB_HOST=db.internal.razorpay.net \
--from-literal=LOG_LEVEL=info -n payments
kubectl get configmap app-config -o yaml -n payments
kubectl get secret db-credentials -n payments \
-o jsonpath='{.data.password}' | base64 -d
kubectl get secret db-credentials -n payments \
-o go-template='{{range $k,$v := .data}}{{$k}}: {{$v|base64decode}}{{"\n"}}{{end}}'
Parameter Breakdown:
-o jsonpath: Extracts a single field from the resource JSON-o go-template with base64decode: Decodes every key in a Secret in one pass--from-literal: Inline key=value pairs — use --from-file for whole config filesDiagnose CrashLoopBackOff, OOMKilled, ImagePullBackOff, and Pending pods.
kubectl describe pod orders-api-7d4b -n payments
## check the Events section at the bottom first
kubectl top pod orders-api-7d4b -n payments ## memory near limit?
kubectl logs orders-api-7d4b --previous ## why did it crash?
kubectl get events -n payments \
--sort-by='.lastTimestamp'
kubectl get events -A --types=Warning ## cluster-wide warnings
Command Parameter Table:
| Symptom | First Command | Look For |
|---|---|---|
| CrashLoopBackOff | logs --previous |
App startup error |
| OOMKilled | top pod |
Memory near limit |
| ImagePullBackOff | describe pod |
Events: auth/registry error |
| Pending | describe pod |
Events: insufficient cpu/no nodes match |
Shape kubectl get output for scripts, dashboards, and quick audits.
kubectl get pods -A -o=custom-columns=\
'NAME:.metadata.name,IMAGE:.spec.containers[*].image'
kubectl get nodes -o jsonpath=\
'{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
kubectl get pods --show-labels
| Format | Description |
|---|---|
-o=wide |
Plain text plus node name and extra columns |
-o=json / -o=yaml |
Full API object in JSON or YAML |
-o=jsonpath=<expr> |
Extract specific fields with a JSONPath expression |
-o=custom-columns=<spec> |
Build a custom table from arbitrary fields |
-o=name |
Resource name only — useful for piping into other commands |
Drain and cordon nodes safely during upgrades.
kubectl get nodes -o wide
kubectl cordon node-3 ## mark unschedulable
kubectl drain node-3 \
--ignore-daemonsets --delete-emptydir-data
kubectl uncordon node-3 ## mark schedulable again
kubectl top node ## cluster-wide resource usage
kubectl taint nodes node-3 \
dedicated=gpu:NoSchedule
kubectl api-resources --namespaced=true
Parameter Breakdown:
drain --ignore-daemonsets: Required or drain will block on DaemonSet-managed podscordon vs drain: Cordon only stops new scheduling; drain actively evicts existing podstaint: Repels pods from a node unless they carry a matching tolerationManage isolation and verify access before debugging a permissions issue.
kubectl create namespace payments-staging
kubectl config set-context --current \
--namespace=payments
kubectl auth can-i create pods -n payments
kubectl auth can-i delete secrets \
--as=system:serviceaccount:payments:api-sa
kubectl get rolebindings -n payments
kubectl describe rolebinding api-role-binding -n payments
Parameter Breakdown:
set-context --current --namespace: Avoids typing -n on every command for a session--as: Impersonates a user or service account to test their actual permissionsauth can-i: Returns yes/no — wire this into CI/CD as a pre-flight permission checkStandard shortcuts most DevOps teams add to their dotfiles.
alias k=kubectl
alias kgp='kubectl get pods'
alias kgpa='kubectl get pods -A'
alias kdp='kubectl describe pod'
alias kl='kubectl logs -f'
## Delete every pod stuck in CrashLoopBackOff
kubectl get pods -A | grep CrashLoopBackOff | \
awk '{print $1, $2}' | xargs -n2 kubectl delete pod -n
## Watch a rollout update live
kubectl get pods -n payments -w
## Copy a file out of a running pod
kubectl cp payments/orders-api-7d4b:/app/logs/app.log ./app.log
Notes:
kubectl tree for visualizing resource ownership and kubectl neat for cleaning noisy YAML output — both are worth installing on any workstation running kubectl daily.kubectl config current-context after a long break before applying anything destructive.