Cheat sheet: Kubernetes
kubectl commands explained part by part: get, describe, logs, exec, rollouts, selectors and output formats.
Each entry shows the command, a copy button, and what every part does: sub-command, flag, pipe, redirect and placeholder, in the order they appear. <placeholders> are the bits you replace.
- Whole sheet137
- Basics: cluster, namespaces & resources17
- Get & list resources23
- Context & namespace3
- Find resources9
- Debug: describe, events, logs8
- Exec, port-forward, copy4
- Deploy, roll out, roll back, scale7
- Cleanup & nodes4
- Services, DNS & networking checks6
- Environment, config & secrets of workloads9
- Create, generate & apply YAML10
- Patch, label, annotate & scale9
- Delete & force delete6
- Nodes, scheduling & access control11
- Productivity: aliases, contexts & output11
Basics: cluster, namespaces & resources17
kubectl versionClient and cluster versionWhat each part does
kubectl versionclient and server versions; add --client for the client only (no cluster needed)
kubectl cluster-infoIs the cluster reachable?What each part does
cluster-infoaddresses of the control plane and core services
kubectl get nodes -o wideList nodesWhat each part does
get nodescluster nodes and whether they are Ready-o wideadd internal/external IP, OS, kernel, container runtime
kubectl get nsList namespacesWhat each part does
get nsshort for get namespaces
kubectl create namespace <namespace>Create a namespaceWhat each part does
create namespacemake a new namespace (short: create ns)
kubectl get all -n <namespace>Everything in a namespaceWhat each part does
get allpods, services, deployments, replicasets, statefulsets, jobs… (not configmaps/secrets/ingress)-n <namespace>--namespace: which namespace
kubectl get deploy,svc,ing -n <namespace>Deployments, services and ingresses at onceWhat each part does
deploy,svc,ingcomma-separated resource types (short names)
kubectl get configmap,secret -n <namespace>ConfigMaps and SecretsWhat each part does
configmap,secretconfig objects (secret values are not shown here)
kubectl get pods -wWatch pods change liveWhat each part does
-w--watch: keep printing updates until Ctrl+C
kubectl get pod <pod> -o yamlFull YAML of a live objectWhat each part does
-o yamloutput the whole object, including status
kubectl apply -f <file-or-dir>Create / update from a fileWhat each part does
applycreate or update to match the manifest-f--filename: a file, a folder or a URL (add -R for sub-folders)
kubectl delete -f <file-or-dir>Delete what a file definesDestructiveWhat each part does
delete -fdelete the objects listed in the manifest
kubectl edit deploy/<deployment>Edit a live object in your editorCautionWhat each part does
editopens the object in $EDITOR (KUBE_EDITOR); saving applies it
kubectl label pod <pod> <key>=<value> --overwriteAdd or change a labelWhat each part does
labelset labels on objects<key>=<value>the label; <key>- (trailing dash) removes it--overwriteallow replacing an existing value
kubectl expose deployment <deployment> --port=80 --target-port=8080 --type=ClusterIPExpose a deployment as a serviceWhat each part does
exposecreate a Service for a workload--port=80port the Service listens on--target-port=8080container port the traffic goes to--type=ClusterIPClusterIP (default, in-cluster), NodePort or LoadBalancer
kubectl run tmp --rm -it --restart=Never --image=busybox:1.36 -- shThrow-away debug pod with a shellWhat each part does
run tmpcreate a pod named tmp--rmdelete it when you exit-itinteractive terminal--restart=Nevera plain pod, not managed by anything--image=busybox:1.36small image with basic tools (nslookup, wget)-- shcommand to run
kubectl get secret <secret> -o jsonpath='{.data.<key>}' | base64 -dRead one value from a SecretCautionWhat each part does
-o jsonpath=…print just that field{.data.<key>}the base64-encoded value of <key>| base64 -ddecode it to plain text
Tip Prints a secret to your terminal.
Get & list resources (short names)23
kubectl get po -n <namespace>List podsWhat each part does
kubectl getlist resourcesposhort name for pods: NAME, READY, STATUS, RESTARTS, AGE-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get po -o wide -n <namespace>List pods with node and IPWhat each part does
popods-o wideadd the pod IP, the node it runs on and nominated node-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get svc -n <namespace>List servicesWhat each part does
svcshort name for services: TYPE, CLUSTER-IP, EXTERNAL-IP, PORT(S)-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get svc -o wide -n <namespace>List services with their selectorsWhat each part does
svc -o wideadd the SELECTOR column: which pod labels the service sends traffic to-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get endpointslices -l kubernetes.io/service-name=<service> -n <namespace>Which pods is a service sending traffic to?What each part does
endpointslicesthe actual pod IPs:ports behind services (kubectl get ep <service> on older clusters)-l kubernetes.io/service-name=<service>only the slices of this service-n <namespace>in this namespace (default: the context's namespace; -A for all)
Tip Empty ENDPOINTS means the selector matches no ready pods: compare kubectl get svc -o wide with kubectl get po --show-labels.
kubectl get deploy -n <namespace>List deploymentsWhat each part does
deploydeployments: READY (ready/desired), UP-TO-DATE, AVAILABLE-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get rs -n <namespace>List ReplicaSetsWhat each part does
rsReplicaSets; old ones with 0 replicas are kept for rollbacks-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get sts,ds -n <namespace>List StatefulSets and DaemonSetsWhat each part does
stsStatefulSetsdsDaemonSets: desired / current / ready per node-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get ing -AList ingressesWhat each part does
ingingresses: class, hosts, address, ports-Aall namespaces
kubectl get cm,secret -n <namespace>List ConfigMaps and SecretsWhat each part does
cmConfigMapssecretSecrets (values are not shown)-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get pv,pvc -AList volumes and claimsWhat each part does
pvPersistentVolumes (cluster-wide): capacity, status, claimpvcPersistentVolumeClaims: Bound / Pending-Aall namespaces for the claims
kubectl get scList storage classesWhat each part does
scStorageClasses; (default) marks the one used when a PVC names none
kubectl get jobs,cj -n <namespace>List jobs and cronjobsWhat each part does
jobsJobs: completions, durationcjCronJobs: schedule, last schedule, active-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get hpa -n <namespace>List autoscalersWhat each part does
hpaHorizontalPodAutoscalers: target metric vs current, min/max/current replicas-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get sa -n <namespace>List service accountsWhat each part does
saServiceAccounts-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get netpol -n <namespace>List network policiesWhat each part does
netpolNetworkPolicies and the pods they select-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get crdList custom resource typesWhat each part does
crdCustomResourceDefinitions installed by operators and add-ons
kubectl api-resources --sort-by=name -o wideEvery short name and resource typeWhat each part does
api-resourcesevery resource type: SHORTNAMES (po, svc, deploy...), API group, namespaced, verbs--sort-by=namealphabetical-o wideinclude supported verbs
kubectl get po -l 'env in (prod,staging),tier!=frontend'Pods by set-based label selectorWhat each part does
-l '...'label selectorenv in (prod,staging)label env is one of thesetier!=frontendand tier is not frontend
kubectl get po -A -o wide --field-selector spec.nodeName=<node>Pods on a specific nodeWhat each part does
-A -o wideall namespaces, with node column--field-selector spec.nodeName=<node>only pods scheduled on that node
kubectl get po -o name -n <namespace>Just the names (for scripts)What each part does
-o nameprint type/name per line, e.g. pod/api-7d9f, ready for xargs-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get po -A -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.image}{"\n"}{end}{end}' | sort | uniq -cEvery image running in the clusterWhat each part does
-o jsonpath='...'loop over pods and their containers, print each image| sort | uniq -ccount pods per image
kubectl get po -w -n <namespace>Watch resources changeWhat each part does
-wkeep printing changes (status, restarts) until Ctrl+C-n <namespace>in this namespace (default: the context's namespace; -A for all)
Context & namespace3
kubectl config current-contextWhich cluster am I talking to?What each part does
kubectl configwork with the kubeconfig filecurrent-contextprint the active context (cluster + user + default namespace)
kubectl config get-contexts; kubectl config use-context <context>List contexts and switchWhat each part does
get-contextsall contexts; * marks the active oneuse-context <context>make <context> the default for later commands
Tip Check twice before running anything against prod.
kubectl config set-context --current --namespace=<namespace>Set the default namespace for this contextWhat each part does
set-contextedit a context--currentthe active one--namespace=<namespace>saved default namespace, so you can drop -n afterwards
Find resources9
kubectl get pods -A -o widePods in every namespace, with node and IPWhat each part does
kubectl get podslist pods-A--all-namespaces-o wideextra columns: node, pod IP, nominated node
kubectl get pods -A | grep <name>Find a pod by name fragmentWhat each part does
kubectl get pods -Aall pods in all namespaces (columns: NAMESPACE NAME READY STATUS…)|pipe the table into grepgrep <name>keep rows containing <name> (pod name, namespace or status like CrashLoopBackOff)
kubectl get pods -A --field-selector=status.phase!=RunningPods that are not RunningWhat each part does
--field-selectorfilter on object fields server-sidestatus.phase!=Runningphase is anything except Running (Pending, Failed, Succeeded, Unknown)
kubectl get pods -l app=<app> --show-labelsPods with a labelWhat each part does
-l app=<app>--selector: label must match (use "!key" to exclude, key in (a,b) for sets)--show-labelsadd a LABELS column
kubectl get pods -n <namespace> --sort-by=.status.containerStatuses[0].restartCountRecently restarted pods, sortedWhat each part does
--sort-by=<jsonpath>sort rows by a field of the object.status.containerStatuses[0].restartCountrestart count of the first container: crash-looping pods end up last
kubectl get pods -o jsonpath='{.items[*].metadata.name}'Just the pod namesWhat each part does
-o jsonpath=…print fields using a JSONPath template{.items[*].metadata.name}the name of every item in the list
kubectl get pods -o custom-columns='NAME:.metadata.name,IMAGE:.spec.containers[*].image'Custom table: pod and imageWhat each part does
-o custom-columns=…build your own tableNAME:.metadata.namecolumn header : JSONPath of the valueIMAGE:.spec.containers[*].imageimages of all containers
kubectl api-resourcesWhat resource types exist (and their short names)What each part does
api-resourcesevery resource type with short name (po, svc, deploy…), API group and whether it is namespaced
kubectl explain deployment.spec.strategyDocs for a fieldWhat each part does
explainbuilt-in documentation for resource fieldsdeployment.spec.strategypath to the field you want to understand
Debug: describe, events, logs8
kubectl describe pod <pod> -n <namespace>Why is a pod not starting?What each part does
describe pod <pod>status, conditions, container states (Last State / Exit Code) and events at the bottom-n <namespace>namespace of the pod
Tip Look for ImagePullBackOff, FailedScheduling, OOMKilled, probe failures in Events.
kubectl get events -n <namespace> --sort-by=.metadata.creationTimestampRecent events, newest lastWhat each part does
get eventscluster events (scheduling, pulls, kills, probe failures)--sort-by=.metadata.creationTimestampoldest → newest
kubectl events -n <namespace> --types=WarningOnly warning eventsWhat each part does
kubectl eventsnewer events subcommand--types=Warningonly Warning-type events
kubectl logs -f <pod> -n <namespace> --tail=200Follow logs of a podWhat each part does
logs <pod>container's stdout/stderr-fstream new lines--tail=200start from the last 200 lines
kubectl logs <pod> -c <container> --previousLogs of the crashed (previous) containerWhat each part does
-c <container>pick a container in a multi-container pod--previouslogs of the previous instance, i.e. the one that crashed
kubectl logs -l app=<app> --all-containers --prefix -fLogs from all pods with a labelWhat each part does
-l app=<app>every pod matching the label--all-containersall containers in each pod--prefixprefix lines with pod/container name-ffollow
kubectl logs deploy/<deployment> --since=1h | grep -i errorGrep logs for errorsWhat each part does
deploy/<deployment>logs from one pod of the deployment--since=1honly the last hour| grep -i errorkeep lines with "error", any case
kubectl top pod -n <namespace> --sort-by=memory --containersCPU / memory usageWhat each part does
top podlive usage (needs metrics-server)--sort-by=memoryhighest memory first (or cpu)--containersper container instead of per pod
Exec, port-forward, copy4
kubectl exec -it <pod> -n <namespace> -- shShell into a podWhat each part does
exec <pod>run a command in a container of the pod-itinteractive stdin + terminal--everything after this is the command, not kubectl flagsshthe shell (bash if available)
kubectl port-forward svc/<service> <local-port>:<service-port> -n <namespace>Reach a service from your laptopWhat each part does
port-forwardtunnel a local port into the clustersvc/<service>target a service (or pod/<pod>, deploy/<name>)<local-port>:<service-port>listen on localhost:<local-port>, forward to <service-port>
kubectl cp <namespace>/<pod>:<path> ./<file>Copy files out of / into a podWhat each part does
cpcopy files (needs tar inside the container)<namespace>/<pod>:<path>source in the pod; swap the arguments to copy into the pod
kubectl debug <pod> -it --image=busybox:1.36 --target=<container>Attach a debug container to a podWhat each part does
debug <pod>add an ephemeral debug container-itinteractive terminal--image=busybox:1.36image with the tools you need--target=<container>share that container's process namespace
Deploy, roll out, roll back, scale7
kubectl diff -f <dir> && kubectl apply -f <dir>Preview then apply manifestsWhat each part does
diff -f <dir>show what would change on the server&&continue only if diff ran without error (diff exits 1 when there are changes; use ; instead if you want to apply anyway)apply -f <dir>create or update every manifest in the folder
kubectl set image deployment/<deployment> <container>=<image>:<tag> -n <namespace>Change the image of a deploymentCautionWhat each part does
set imageupdate container images → triggers a rolling updatedeployment/<deployment>which deployment<container>=<image>:<tag>container name in the pod spec = new image
kubectl rollout status deployment/<deployment> --timeout=5mWait for the rollout to finishWhat each part does
rollout statuswatch progress until done or failed--timeout=5mgive up (non-zero exit) after 5 minutes: good for CI
kubectl rollout history deployment/<deployment>; kubectl rollout undo deployment/<deployment> --to-revision=<n>History and rollbackCautionWhat each part does
rollout historylist revisionsrollout undogo back to the previous revision--to-revision=<n>or to a specific revision from the history
kubectl rollout restart deployment/<deployment> -n <namespace>Restart all pods of a deploymentCautionWhat each part does
rollout restartrolling restart without changing the spec (picks up new ConfigMap/Secret values)
kubectl scale deployment/<deployment> --replicas=<n>Scale replicasCautionWhat each part does
scaleset the desired replica count--replicas=<n>new count (0 stops the app)
kubectl create deployment <name> --image=<image> --dry-run=client -o yaml > deploy.yamlGenerate a manifest without creating anythingWhat each part does
create deploymentbuild a Deployment object--dry-run=clientdon't send it to the cluster-o yamlprint it as YAML> deploy.yamlsave to a file to edit and commit
Cleanup & nodes4
kubectl delete pods -n <namespace> --field-selector=status.phase=FailedDelete failed / evicted podsDestructiveWhat each part does
delete podsdelete pods…--field-selector=status.phase=Failed…but only those in phase Failed (includes Evicted)
kubectl get pods -n <namespace> --no-headers | awk '/<pattern>/{print $1}' | xargs -r kubectl delete pod -n <namespace>Delete pods whose name matches a patternDestructiveWhat each part does
--no-headersdrop the header row so only data lines go throughawk '/<pattern>/{print $1}'for lines matching <pattern>, print column 1 (the pod name)xargs -r kubectl delete poddelete each name; -r: skip if nothing matched
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data; kubectl uncordon <node>Take a node out for maintenance and backCautionWhat each part does
drain <node>cordon the node and evict its pods--ignore-daemonsetsdon't fail on DaemonSet pods (they stay)--delete-emptydir-dataallow evicting pods that use emptyDir (that data is lost)uncordon <node>make it schedulable again
kubectl top node; kubectl describe node <node>Node usage and detailsWhat each part does
top nodeCPU/memory per nodedescribe nodecapacity, allocatable, conditions (DiskPressure, MemoryPressure) and pods on it
Services, DNS & networking checks6
kubectl describe svc <service> -n <namespace>Describe a serviceWhat each part does
describe svctype, selector, ports, target ports, endpoints and events-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl run dnstest --rm -it --restart=Never --image=busybox:1.36 -- nslookup <service>.<namespace>.svc.cluster.localTest DNS from inside the clusterWhat each part does
kubectl run dnstest --rm -it --restart=Neverthrowaway pod, removed when done--image=busybox:1.36small image with nslookup<service>.<namespace>.svc.cluster.locala service's full DNS name
kubectl run curltest --rm -it --restart=Never --image=curlimages/curl -- curl -sv http://<service>.<namespace>:<port>/Call a service from inside the clusterWhat each part does
--image=curlimages/curlimage with curlhttp://<service>.<namespace>:<port>/service DNS name and port: tests the path pods use
kubectl port-forward deploy/<deployment> <local-port>:<container-port> -n <namespace>Port-forward to a deployment or podWhat each part does
deploy/<deployment>picks one pod of the deployment (also pod/<pod>, svc/<service>)<local-port>:<container-port>localhost port : port in the pod-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl proxy --port=8001Open a local proxy to the API serverWhat each part does
kubectl proxyauthenticated proxy: http://localhost:8001/api/... reaches the API, and services via /api/v1/namespaces/<ns>/services/<svc>/proxy/--port=8001local port
kubectl get --raw='/readyz?verbose'Check the API server healthWhat each part does
get --rawcall an API path directly/readyz?verboseeach readiness check with ok/failed (also /livez)
Environment, config & secrets of workloads9
kubectl exec <pod> -n <namespace> -- envPrint env vars of a running podWhat each part does
kubectl exec <pod>run in the pod (add -c <container>)-n <namespace>in this namespace (default: the context's namespace; -A for all)-- envprint all environment variables
kubectl set env deploy/<deployment> --list -n <namespace>Env vars set on a deployment (incl. from ConfigMaps/Secrets)What each part does
set env ... --listlist the env defined in the pod template, showing which come from configMapKeyRef / secretKeyRef-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl set env deploy/<deployment> <KEY>=<value> -n <namespace>; kubectl set env deploy/<deployment> <KEY>- -n <namespace>Set or remove an env var (triggers a rollout)CautionWhat each part does
<KEY>=<value>add or change<KEY>-trailing minus removes it
kubectl create configmap <name> --from-literal=<key>=<value> --from-file=<path> -n <namespace>Create a ConfigMap from literals or a fileWhat each part does
create configmap <name>new ConfigMap--from-literal=<key>=<value>one key/value--from-file=<path>file content (key = file name), or a whole directory
kubectl create secret generic <name> --from-literal=<key>=<value> -n <namespace>Create a generic secretWhat each part does
secret genericOpaque secret--from-literalvalue from the command line (lands in shell history: prefer --from-file or --from-env-file)
kubectl create secret docker-registry <name> --docker-server=<registry> --docker-username=<user> --docker-password=<token> -n <namespace>Create an image pull secretWhat each part does
secret docker-registrycredentials for a private registry; reference it in imagePullSecrets
kubectl create secret tls <name> --cert=<cert>.pem --key=<key>.pem -n <namespace>Create a TLS secretWhat each part does
secret tlskubernetes.io/tls secret used by ingresses--cert / --keyPEM certificate (with chain) and private key
kubectl get secret <secret> -n <namespace> -o go-template='{{range $k,$v := .data}}{{$k}}={{$v | base64decode}}{{"\n"}}{{end}}'Decode all keys of a secretWhat each part does
-o go-template='...'loop over every key and base64-decode the value
Tip Prints secrets in clear text on your screen.
kubectl create configmap <name> --from-file=<path> --dry-run=client -o yaml | kubectl apply -f -Update a ConfigMap from a file (apply-style)What each part does
--dry-run=client -o yamlgenerate the manifest without creating| kubectl apply -f -create or update it
Tip Pods only see new values after a restart (env) or after the kubelet syncs (mounted files).
Create, generate & apply YAML10
kubectl run <name> --image=<image> --port=<port> --dry-run=client -o yaml > pod.yamlGenerate a pod manifestWhat each part does
kubectl run <name> --image=<image>a single pod (the old --generator flag is gone)--dry-run=client -o yamlprint YAML instead of creating> pod.yamlsave to edit
kubectl expose deploy <deployment> --port=<port> --target-port=<container-port> --dry-run=client -o yaml > svc.yamlGenerate a service manifestWhat each part does
expose deploy <deployment>service selecting the deployment's pods--port / --target-portservice port / container port--dry-run=client -o yamlYAML only
kubectl create job <job-name> --from=cronjob/<cronjob> -n <namespace>Create a job from a cronjob (run it now)What each part does
create job --from=cronjob/<cronjob>one-off Job using the CronJob's template-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl create cronjob <name> --image=<image> --schedule='*/5 * * * *' -- <command>Create a cronjobWhat each part does
--schedule='...'cron schedule-- <command>what the container runs
kubectl get deploy <deployment> -n <namespace> -o yaml > deploy.yamlExport an existing object as clean YAMLWhat each part does
-o yamlthe full object; remove status, metadata.uid, resourceVersion, managedFields before re-applying (--export no longer exists; the kubectl-neat plugin strips them)
kubectl apply -R -f <dir>Apply a directory recursivelyWhat each part does
-Rrecurse into subdirectories-f <dir>every manifest in it
kubectl apply -k <overlay-dir>Apply a Kustomize overlayWhat each part does
-k <dir>render kustomization.yaml and apply; kubectl kustomize <dir> just prints it
kubectl apply --server-side -f <file>Server-side applyWhat each part does
--server-sidethe API server merges and tracks field ownership; needed for large CRDs
kubectl replace --force -f <file>Replace an object (delete + recreate)CautionWhat each part does
replace --forcedelete and recreate: for fields that can't be changed in place
kubectl wait --for=condition=Ready pod -l app=<app> --timeout=120s -n <namespace>Wait until pods are readyWhat each part does
kubectl wait --for=condition=Readyblock until the condition is true (also --for=delete, --for=jsonpath=...)pod -l app=<app>which objects--timeout=120sfail after 2 minutes
Patch, label, annotate & scale9
kubectl patch deploy <deployment> -n <namespace> -p '{"spec":{"replicas":3}}'Patch a field (strategic merge)CautionWhat each part does
patchchange part of a live object without a full manifest-p '{...}'JSON or YAML snippet merged into the object
kubectl patch svc <service> --type=json -p '[{"op":"replace","path":"/spec/type","value":"NodePort"}]'Patch with a JSON patchCautionWhat each part does
--type=jsonRFC 6902 operations: add, remove, replace at a path-p '[...]'the operations
kubectl label po <pod> <key>=<value>; kubectl label po <pod> <key>-Add / remove a labelWhat each part does
<key>=<value>add (add --overwrite to change)<key>-remove the label; also a way to take a pod out of a service for debugging
kubectl annotate deploy <deployment> <key>='<value>' --overwriteAdd an annotationWhat each part does
annotatenon-identifying metadata read by tools--overwritereplace an existing value
kubectl autoscale deploy <deployment> --min=2 --max=10 --cpu-percent=80Autoscale a deploymentWhat each part does
autoscalecreate an HPA--min / --maxreplica bounds--cpu-percent=80target average CPU vs requests (pods need CPU requests)
kubectl set resources deploy <deployment> -c <container> --requests=cpu=100m,memory=128Mi --limits=memory=256MiSet CPU / memory requests and limitsCautionWhat each part does
set resourceschange resources in the pod template (rollout follows)--requests / --limitsvalues per container
kubectl rollout pause deploy/<deployment>; kubectl rollout resume deploy/<deployment>Pause and resume a rolloutWhat each part does
rollout pausestop rolling out; batch several changesrollout resumeroll them out together
kubectl rollout history deploy/<deployment> --revision=<n>Details of one rollout revisionWhat each part does
--revision=<n>show the pod template (images, env) of that revision before undoing to it
kubectl scale sts <statefulset> --replicas=<n> -n <namespace>Scale a StatefulSetWhat each part does
scale stspods are added/removed in order (highest ordinal first on scale-down)
Delete & force delete6
kubectl delete po <pod> -n <namespace>Delete a pod (its controller recreates it)CautionWhat each part does
delete po <pod>graceful delete; a Deployment/StatefulSet makes a new one-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl delete po <pod> -n <namespace> --grace-period=0 --forceForce delete a stuck podDestructiveWhat each part does
--grace-period=0 --forceremove from the API immediately without waiting for the kubelet (pod stuck in Terminating)
Tip The container may still be running on the node; for StatefulSets this can cause two pods with the same identity.
kubectl delete po,svc -l app=<app> -n <namespace>Delete by labelDestructiveWhat each part does
po,svcseveral types at once-l app=<app>everything with that label
kubectl delete <type> <name> -n <namespace>Delete a resource by type and nameDestructiveWhat each part does
<type> <name>e.g. deploy api, svc api, cm app-config, rs api-7d9f
kubectl delete all --all -n <namespace>Delete everything in a namespace (keep the namespace)DestructiveWhat each part does
allpods, services, deployments, replicasets, statefulsets, jobs (not configmaps, secrets, PVCs)--allevery object of those types
kubectl delete ns <namespace>Delete a namespace and everything in itDestructiveWhat each part does
delete nsremoves the namespace and all objects in it, including PVCs and secrets
Nodes, scheduling & access control11
kubectl cordon <node>Stop new pods landing on a nodeWhat each part does
cordonmark unschedulable; running pods stay (drain to evict them, uncordon to undo)
kubectl taint nodes <node> <key>=<value>:NoSchedule; kubectl taint nodes <node> <key>:NoSchedule-Taint a node / remove a taintWhat each part does
<key>=<value>:NoScheduleonly pods tolerating this taint can schedule here (NoExecute also evicts)<key>:NoSchedule-trailing minus removes it
kubectl label node <node> <key>=<value>Label a nodeWhat each part does
label nodeused by nodeSelector / affinity, e.g. disktype=ssd
kubectl get nodes --show-labels; kubectl describe node <node> | grep -A3 TaintsNode labels and taintsWhat each part does
--show-labelsall labels (zone, instance type, OS, arch)grep -A3 Taintstaints on the node
kubectl describe node <node> | grep -A8 'Allocated resources'How full is a node? (requests vs capacity)What each part does
Allocated resourcessum of CPU/memory requests and limits vs allocatable: why pods are Pending even if usage is low
kubectl auth can-i <verb> <resource> -n <namespace> --as=<user-or-sa>Can I (or someone) do this?What each part does
auth can-iyes/no for an action, e.g. can-i delete pods--as=<user-or-sa>impersonate, e.g. system:serviceaccount:<ns>:<sa>
kubectl auth can-i --list -n <namespace>Everything I am allowed to doWhat each part does
--listall verbs per resource for the current user in that namespace
kubectl auth whoamiWho am I logged in as?What each part does
auth whoamiuser name and groups the API server sees for your credentials
kubectl create token <serviceaccount> -n <namespace> --duration=1hCreate a short-lived token for a service accountWhat each part does
create tokenrequest a bound token (no long-lived secret)--duration=1hlifetime
kubectl get csr; kubectl certificate approve <csr>Approve a certificate signing requestCautionWhat each part does
get csrpending node / user certificate requestscertificate approvesign it
kubectl versionClient and server versionsWhat each part does
kubectl versionclient and API server versions; keep kubectl within one minor version of the server
Productivity: aliases, contexts & output11
alias k=kubectl; source <(kubectl completion bash); complete -o default -F __start_kubectl kShort alias with completion (bash)What each part does
alias k=kubectltype k get po instead of kubectl get podskubectl completion bashtab completion for resources and names (zsh: completion zsh)complete ... kmake completion work for the alias too
Tip PowerShell: Set-Alias -Name k -Value kubectl. Put these in ~/.bashrc to keep them.
kubectl config get-clusters; kubectl config get-usersList clusters and users in kubeconfigWhat each part does
get-clusterscluster entriesget-userscredential entries
kubectl config view --minifyShow the current context's config onlyWhat each part does
config viewkubeconfig contents (secrets redacted)--minifyonly what the current context uses
KUBECONFIG=~/.kube/config:<other-config> kubectl config view --flatten > merged-configMerge several kubeconfig filesWhat each part does
KUBECONFIG=a:bcolon-separated list of files kubectl reads togetherview --flattenone self-contained file
kubectl config delete-context <context>Remove a contextWhat each part does
delete-contextremove it from kubeconfig (cluster and user entries stay)
kubectx <context>; kubens <namespace>Switch context / namespace quicklyWhat each part does
kubectxswitch context (plugin)kubensswitch default namespace
kubectl explain pod.spec.containers --recursive | lessExplain every field of a resourceWhat each part does
explain <path>docs for a field--recursivethe whole tree of sub-fields
kubectl get po -A --sort-by=.metadata.creationTimestampSort outputWhat each part does
--sort-by=<jsonpath>sort by any field: creation time, .status.startTime, restartCount...
kubectl plugin list; kubectl krew listList kubectl pluginsWhat each part does
plugin listkubectl-* binaries on your PATHkrew listplugins installed with the krew plugin manager
kubectl attach -it <pod> -c <container>Attach to a running containerWhat each part does
attachconnect to the main process's stdin/stdout (exec starts a new process instead)
kubectl get po -v=6Show more detail about what kubectl doesWhat each part does
-v=6log the API calls kubectl makes (8 includes bodies): useful for auth and timeout problems
Nothing matches.
My DevOps Playbook by Angelo John Calleja