kubectl quick Reference
This cheat sheet is adapted from the official Kubernetes quick reference and focused on hands-on practice in the simulator. Not every command is supported in the simulator.
Practicing these commands repeatedly in the terminal helps build muscle memory for real troubleshooting and exam-like workflows.
Source: Kubernetes kubectl Quick Reference
Note: this quick reference is based on Kubernetes
v1.35.
Kubectl context and configuration
kubectl config view # Show merged kubeconfig settings.
# use multiple kubeconfig files at the same time and view merged configKUBECONFIG=~/.kube/config:~/.kube/kubconfig2kubectl config view
# show merged kubeconfig settings and raw certificate data and exposed secretskubectl config view --raw
# get the password for the e2e userkubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'
# get the certificate for the e2e userkubectl config view --raw -o jsonpath='{.users[?(.name == "e2e")].user.client-certificate-data}' | base64 -d
kubectl config view -o jsonpath='{.users[].name}' # display the first userkubectl config view -o jsonpath='{.users[*].name}' # get a list of userskubectl config get-contexts # display list of contextskubectl config get-contexts -o name # get all context nameskubectl config current-context # display the current-contextkubectl config use-context my-cluster-name # set the default context to my-cluster-namekubectl config set-cluster my-cluster-name # set a cluster entry in kubeconfigkubectl config set-cluster my-cluster-name --proxy-url=my-proxy-urlkubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepasswordkubectl config set-context --current --namespace=ggckad-s2kubectl config set-context gce --user=cluster-admin --namespace=foo && kubectl config use-context gcekubectl config unset users.fooKubectl apply
apply creates or updates resources from files. It is the recommended workflow for declarative resource management.
Creating objects
kubectl apply -f ./my-manifest.yamlkubectl apply -f ./my1.yaml -f ./my2.yamlkubectl apply -f ./dirkubectl apply -f https://example.com/manifest.yamlkubectl create deployment nginx --image=nginxkubectl create job hello --image=busybox:1.28 -- echo "Hello World"kubectl create cronjob hello --image=busybox:1.28 --schedule="*/1 * * * *" -- echo "Hello World"kubectl explain podsCreate multiple objects from stdin:
apiVersion: v1kind: Podmetadata: name: busybox-sleepspec: containers: - name: busybox image: busybox:1.28 args: - sleep - '1000000'---apiVersion: v1kind: Podmetadata: name: busybox-sleep-lessspec: containers: - name: busybox image: busybox:1.28 args: - sleep - '1000'kubectl apply -f busybox-sleep-pods.yamlCreate a secret from stdin:
apiVersion: v1kind: Secretmetadata: name: mysecrettype: Opaquedata: password: $(echo -n "s33msi4" | base64 -w0) username: $(echo -n "jane" | base64 -w0)kubectl apply -f mysecret.yamlViewing and finding resources
kubectl get serviceskubectl get pods --all-namespaceskubectl get pods -o widekubectl get deployment my-depkubectl get podskubectl get pod my-pod -o yamlkubectl describe nodes my-nodekubectl describe pods my-podkubectl get services --sort-by=.metadata.namekubectl get pods --sort-by='.status.containerStatuses[0].restartCount'kubectl get pv --sort-by=.spec.capacity.storagekubectl get pods --selector=app=cassandra -o jsonpath='{.items[*].metadata.labels.version}'kubectl get configmap myconfig -o jsonpath='{.data.ca\.crt}'kubectl get secret my-secret --template='{{index .data "key-name-with-dashes"}}'kubectl get node --selector='!node-role.kubernetes.io/control-plane'kubectl get pods --field-selector=status.phase=Runningkubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'kubectl get pods --show-labelsMore advanced checks:
JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"kubectl get node -o custom-columns='NODE_NAME:.metadata.name,STATUS:.status.conditions[?(@.type=="Ready")].status'kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{"### "}}{{$k}}{{"\n"}}{{$v|base64decode}}{{"\n\n"}}{{end}}'kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniqkubectl get pods --all-namespaces -o jsonpath='{range .items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -f3kubectl get events --sort-by=.metadata.creationTimestampkubectl events --types=Warningkubectl diff -f ./my-manifest.yamlkubectl get nodes -o json | jq -c 'paths|join(".")'kubectl get pods -o json | jq -c 'paths|join(".")'for pod in $(kubectl get po --output=jsonpath={.items..metadata.name}); do echo $pod && kubectl exec -it $pod -- env; donekubectl get deployment nginx-deployment --subresource=statusUpdating resources
kubectl set image deployment/frontend www=image:v2kubectl rollout history deployment/frontendkubectl rollout undo deployment/frontendkubectl rollout undo deployment/frontend --to-revision=2kubectl rollout status -w deployment/frontendkubectl rollout restart deployment/frontendcat pod.json | kubectl replace -f -kubectl replace --force -f ./pod.jsonkubectl expose rc nginx --port=80 --target-port=8000kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -kubectl label pods my-pod new-label=awesomekubectl label pods my-pod new-label-kubectl label pods my-pod new-label=new-value --overwritekubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWqkubectl annotate pods my-pod icon-url-kubectl autoscale deployment foo --min=2 --max=10Patching resources
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'kubectl patch pod valid-pod --type='json' -p='[{"op":"replace","path":"/spec/containers/0/image","value":"new image"}]'kubectl patch deployment valid-deployment --type json -p='[{"op":"remove","path":"/spec/template/spec/containers/0/livenessProbe"}]'kubectl patch sa default --type='json' -p='[{"op":"add","path":"/secrets/1","value":{"name":"whatever"}}]'kubectl patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{"spec":{"replicas":2}}'Editing resources
kubectl edit svc/docker-registryKUBE_EDITOR="nano" kubectl edit svc/docker-registryScaling resources
kubectl scale --replicas=3 rs/fookubectl scale --replicas=3 -f foo.yamlkubectl scale --current-replicas=2 --replicas=3 deployment/mysqlkubectl scale --replicas=5 rc/foo rc/bar rc/bazDeleting resources
kubectl delete -f ./pod.jsonkubectl delete pod unwanted --nowkubectl delete pod,service baz fookubectl delete pods,services -l name=myLabelkubectl -n my-ns delete pod,svc --allkubectl get pods -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs kubectl delete -n mynamespace podInteracting with running pods
kubectl logs my-podkubectl logs -l name=myLabelkubectl logs my-pod --previouskubectl logs my-pod -c my-containerkubectl logs -l name=myLabel -c my-containerkubectl logs my-pod -c my-container --previouskubectl logs -f my-podkubectl logs -f my-pod -c my-containerkubectl logs -f -l name=myLabel --all-containerskubectl run -i --tty busybox --image=busybox:1.28 -- shkubectl run nginx --image=nginx -n mynamespacekubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yamlkubectl attach my-pod -ikubectl port-forward my-pod 5000:6000kubectl exec my-pod -- ls /kubectl exec --stdin --tty my-pod -- /bin/shkubectl exec my-pod -c my-container -- ls /kubectl debug my-pod -it --image=busybox:1.28kubectl debug node/my-node -it --image=busybox:1.28kubectl top podkubectl top pod POD_NAME --containerskubectl top pod POD_NAME --sort-by=cpuCopying files and directories to and from containers
kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dirkubectl cp /tmp/foo my-pod:/tmp/bar -c my-containerkubectl cp /tmp/foo my-namespace/my-pod:/tmp/barkubectl cp my-namespace/my-pod:/tmp/foo /tmp/barIf tar is not present in the container image:
tar cf - /tmp/foo | kubectl exec -i -n my-namespace my-pod -- tar xf - -C /tmp/barkubectl exec -n my-namespace my-pod -- tar cf - /tmp/foo | tar xf - -C /tmp/barInteracting with deployments and services
kubectl logs deploy/my-deploymentkubectl logs deploy/my-deployment -c my-containerkubectl port-forward svc/my-service 5000kubectl port-forward svc/my-service 5000:my-service-portkubectl port-forward deploy/my-deployment 5000:6000kubectl exec deploy/my-deployment -- lsInteracting with nodes and cluster
kubectl cordon my-nodekubectl drain my-nodekubectl uncordon my-nodekubectl top nodekubectl top node my-nodekubectl cluster-infokubectl cluster-info dumpkubectl cluster-info dump --output-directory=/path/to/cluster-statekubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect'kubectl taint nodes foo dedicated=special-user:NoScheduleResource types
kubectl api-resourceskubectl api-resources --namespaced=truekubectl api-resources --namespaced=falsekubectl api-resources -o namekubectl api-resources -o widekubectl api-resources --verbs=list,getkubectl api-resources --api-group=extensionsFormatting output
| Output format | Description |
|---|---|
-o=custom-columns=<spec> | Print table using custom columns |
-o=custom-columns-file=<filename> | Print table from custom columns file |
-o=go-template=<template> | Print fields from golang template |
-o=go-template-file=<filename> | Print fields from golang template file |
-o=json | Output JSON API object |
-o=jsonpath=<template> | Print fields from jsonpath expression |
-o=jsonpath-file=<filename> | Print fields from jsonpath file |
-o=kyaml | Output KYAML API object |
-o=name | Print resource name only |
-o=wide | Output in extended table format |
-o=yaml | Output YAML API object |
Examples:
kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'kubectl get pods --namespace default --output=custom-columns="NAME:.metadata.name,IMAGE:.spec.containers[*].image"kubectl get pods -A -o=custom-columns='DATA:spec.containers[?(@.image!="registry.k8s.io/coredns:1.6.2")].image'kubectl get pods -A -o=custom-columns='DATA:metadata.*'Kubectl output verbosity and debugging
| Verbosity | Description |
|---|---|
--v=0 | Always-visible operator information |
--v=1 | Reasonable default log level |
--v=2 | Recommended default for most systems |
--v=3 | Extended information about changes |
--v=4 | Debug level verbosity |
--v=5 | Trace level verbosity |
--v=6 | Display requested resources |
--v=7 | Display HTTP request headers |
--v=8 | Display HTTP request contents |
--v=9 | Display full HTTP request contents |