All resources
Kubernetes · Cheat sheet

kubectl cheat sheet

The complete kubectl reference, beginner to advanced: contexts, inspecting and creating resources, rollouts, debugging, RBAC, scheduling, and power-user JSONPath — with example output.

Cluster & contextBeginner
kubectl version --short
Client and server versions.
kubectl cluster-info
Control-plane and CoreDNS endpoints.
kubectl config get-contexts
List every cluster you can talk to.
CURRENT   NAME       CLUSTER    NAMESPACE
*         prod       prod       default
          staging    staging    apps
kubectl config use-context <ctx>
Switch the active cluster.
kubectl config set-context --current --namespace=<ns>
Pin a default namespace so you stop typing -n.
kubectl config current-context
Print just the active context name.
kubectl api-resources
Every resource kind, its short name and apiGroup.
NAME     SHORTNAMES  APIVERSION  NAMESPACED  KIND
pods     po          v1          true        Pod
services svc         v1          true        Service
kubectl api-versions
All served API group/versions.
Inspect resourcesBeginner
kubectl get pods
Pods in the current namespace.
kubectl get pods -A
Pods in every namespace (--all-namespaces).
kubectl get pods -o wide
Add node, pod IP and nominated-node columns.
NAME       READY   STATUS    NODE     IP
web-0      1/1     Running   node-2   10.1.3.7
kubectl get all -n <ns>
Common objects (pods, svc, deploy, rs) at once.
kubectl get pods -w
Watch — stream status changes live.
kubectl get pods -l app=web
Filter by label selector.
kubectl get pods --field-selector status.phase=Running
Filter by a field, not a label.
kubectl get pods --sort-by=.status.startTime
Sort rows by any field path.
kubectl describe pod <p>
Events, conditions, and why it is not Running.
kubectl get events --sort-by=.lastTimestamp
Recent cluster events, oldest→newest.
kubectl get pod <p> -o yaml
Full live manifest of one object.
Create & runBeginner
kubectl run web --image=nginx
Create a single pod imperatively.
kubectl create deployment web --image=nginx --replicas=3
Create a Deployment.
kubectl expose deployment web --port=80 --target-port=8080
Create a Service in front of it.
kubectl apply -f app.yaml
Create/update from a manifest (declarative).
kubectl apply -f .
Apply every manifest in the directory.
kubectl apply -k overlays/prod
Apply a Kustomize overlay.
kubectl create configmap cfg --from-file=./conf.d
ConfigMap from files in a directory.
kubectl create secret generic db --from-literal=pass=s3cr3t
Secret from a literal value.
kubectl create namespace <ns>
Create a namespace.
Edit, scale & rolloutIntermediate
kubectl edit deploy/<d>
Open the live object in $EDITOR and apply on save.
kubectl scale deploy/<d> --replicas=5
Change replica count imperatively.
kubectl set image deploy/<d> app=nginx:1.27
Update one container image → triggers a rollout.
kubectl rollout status deploy/<d>
Watch a rollout to completion.
Waiting for deployment "web" rollout to finish: 2 of 3 updated...
deployment "web" successfully rolled out
kubectl rollout history deploy/<d>
List revisions you can roll back to.
kubectl rollout undo deploy/<d>
Roll back to the previous revision.
kubectl rollout undo deploy/<d> --to-revision=3
Roll back to a specific revision.
kubectl rollout restart deploy/<d>
Restart all pods (re-pull image / reload config).
kubectl autoscale deploy/<d> --min=2 --max=10 --cpu-percent=70
Create a HorizontalPodAutoscaler.
kubectl patch deploy/<d> -p '{"spec":{"replicas":4}}'
Strategic-merge patch one field.
kubectl label pod <p> tier=frontend --overwrite
Add or change a label in place.
kubectl annotate pod <p> note="drain me"
Attach non-identifying metadata.
Debug & logsIntermediate
kubectl logs <p>
Print a container’s logs.
kubectl logs <p> -f
Stream (follow) the logs.
kubectl logs <p> -c <ctr>
Logs from a specific container in the pod.
kubectl logs <p> --previous
Logs from the last crashed instance.
kubectl logs <p> --since=1h --tail=100
Last hour, last 100 lines.
kubectl exec -it <p> -- sh
Open a shell in a running container.
kubectl exec <p> -- env
Run a one-off command and print its output.
kubectl cp <p>:/var/log/app.log ./app.log
Copy a file out of a container.
kubectl port-forward svc/<s> 8080:80
Tunnel a Service to localhost:8080.
kubectl debug <p> -it --image=busybox --target=<ctr>
Attach an ephemeral debug container.
kubectl top pod
Live CPU/memory per pod (needs metrics-server).
NAME     CPU(cores)   MEMORY(bytes)
web-0    3m           28Mi
kubectl top node
Live CPU/memory per node.
Manifests & dry-runIntermediate
kubectl apply -f app.yaml --dry-run=server
Validate against the API without persisting.
kubectl diff -f app.yaml
Show exactly what apply would change.
kubectl create deploy web --image=nginx --dry-run=client -o yaml
Generate a manifest instead of creating.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
...
kubectl get deploy/<d> -o yaml > deploy.yaml
Export a live object to a file.
kubectl explain pod.spec.containers
Field-level docs for any resource.
kubectl replace -f app.yaml
Replace an object wholesale (must exist).
kubectl delete -f app.yaml
Delete everything defined in a manifest.
kubectl delete pod <p> --grace-period=0 --force
Force-remove a stuck pod (last resort).
Namespaces & RBACAdvanced
kubectl auth can-i create pods
Check your own permission.
yes
kubectl auth can-i "*" "*" --all-namespaces
Am I effectively cluster-admin?
kubectl auth can-i list secrets --as=system:serviceaccount:app:build
Check what a ServiceAccount can do.
kubectl create serviceaccount build -n app
Create a ServiceAccount.
kubectl create role reader --verb=get,list --resource=pods -n app
Namespaced Role.
kubectl create rolebinding read-b --role=reader --serviceaccount=app:build -n app
Bind the Role to the SA.
kubectl create clusterrole nodes-ro --verb=get,list --resource=nodes
Cluster-scoped role.
kubectl get rolebindings,clusterrolebindings -A -o wide
Audit who is bound to what.
Nodes & schedulingAdvanced
kubectl get nodes -o wide
Nodes with roles, versions and internal IPs.
kubectl cordon <node>
Mark a node unschedulable (no new pods).
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data
Evict pods to prep for maintenance.
kubectl uncordon <node>
Re-enable scheduling on the node.
kubectl taint nodes <node> key=value:NoSchedule
Repel pods that lack the matching toleration.
kubectl taint nodes <node> key:NoSchedule-
Remove a taint (trailing dash).
kubectl label node <node> disk=ssd
Label a node for nodeSelector/affinity.
kubectl describe node <node>
Capacity, allocatable, taints, and running pods.
JSONPath & power-userAdvanced
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
Extract just the fields you need.
web-0 web-1 api-0
kubectl get pod <p> -o jsonpath='{.status.containerStatuses[0].restartCount}'
Pull one scalar out of an object.
kubectl get svc -o custom-columns=NAME:.metadata.name,IP:.spec.clusterIP
Define your own table columns.
kubectl wait --for=condition=Ready pod/<p> --timeout=120s
Block in scripts until a condition holds.
kubectl apply --server-side -f app.yaml
Server-side apply — safer field ownership.
kubectl get --raw /metrics
Hit an API endpoint directly (raw).
kubectl proxy --port=8001
Local authenticated proxy to the API server.
kubectl certificate approve <csr>
Approve a pending CertificateSigningRequest.
kubectl get pods -o json | jq '.items[].metadata.name'
Pipe JSON to jq for anything JSONPath cannot do.
Go deeper
Full, hands-on DevSecOps courses
Browse courses