Skip to content

Cheat sheet: Kubernetes

kubectl commands explained part by part: get, describe, logs, exec, rollouts, selectors and output formats.

Index
  • #cheatsheet
  • #kubernetes
Updated

Also:k8s · kubectl · jsonpath · custom-columns · field-selector

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.

137 items
Click a command to see what each part does.

Basics: cluster, namespaces & resources17

  • kubectl versionClient and cluster version

    What each part does

    1. kubectl versionclient and server versions; add --client for the client only (no cluster needed)
  • kubectl cluster-infoIs the cluster reachable?

    What each part does

    1. cluster-infoaddresses of the control plane and core services
  • kubectl get nodes -o wideList nodes

    What each part does

    1. get nodescluster nodes and whether they are Ready
    2. -o wideadd internal/external IP, OS, kernel, container runtime
  • kubectl get nsList namespaces

    What each part does

    1. get nsshort for get namespaces
  • kubectl create namespace <namespace>Create a namespace

    What each part does

    1. create namespacemake a new namespace (short: create ns)
  • kubectl get all -n <namespace>Everything in a namespace

    What each part does

    1. get allpods, services, deployments, replicasets, statefulsets, jobs… (not configmaps/secrets/ingress)
    2. -n <namespace>--namespace: which namespace
  • kubectl get deploy,svc,ing -n <namespace>Deployments, services and ingresses at once

    What each part does

    1. deploy,svc,ingcomma-separated resource types (short names)
  • kubectl get configmap,secret -n <namespace>ConfigMaps and Secrets

    What each part does

    1. configmap,secretconfig objects (secret values are not shown here)
  • kubectl get pods -wWatch pods change live

    What each part does

    1. -w--watch: keep printing updates until Ctrl+C
  • kubectl get pod <pod> -o yamlFull YAML of a live object

    What each part does

    1. -o yamloutput the whole object, including status
  • kubectl apply -f <file-or-dir>Create / update from a file

    What each part does

    1. applycreate or update to match the manifest
    2. -f--filename: a file, a folder or a URL (add -R for sub-folders)
  • kubectl delete -f <file-or-dir>Delete what a file definesDestructive

    What each part does

    1. delete -fdelete the objects listed in the manifest
  • kubectl edit deploy/<deployment>Edit a live object in your editorCaution

    What each part does

    1. editopens the object in $EDITOR (KUBE_EDITOR); saving applies it
  • kubectl label pod <pod> <key>=<value> --overwriteAdd or change a label

    What each part does

    1. labelset labels on objects
    2. <key>=<value>the label; <key>- (trailing dash) removes it
    3. --overwriteallow replacing an existing value
  • kubectl expose deployment <deployment> --port=80 --target-port=8080 --type=ClusterIPExpose a deployment as a service

    What each part does

    1. exposecreate a Service for a workload
    2. --port=80port the Service listens on
    3. --target-port=8080container port the traffic goes to
    4. --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 shell

    What each part does

    1. run tmpcreate a pod named tmp
    2. --rmdelete it when you exit
    3. -itinteractive terminal
    4. --restart=Nevera plain pod, not managed by anything
    5. --image=busybox:1.36small image with basic tools (nslookup, wget)
    6. -- shcommand to run
  • kubectl get secret <secret> -o jsonpath='{.data.<key>}' | base64 -dRead one value from a SecretCaution

    What each part does

    1. -o jsonpath=…print just that field
    2. {.data.<key>}the base64-encoded value of <key>
    3. | 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 pods

    What each part does

    1. kubectl getlist resources
    2. poshort name for pods: NAME, READY, STATUS, RESTARTS, AGE
    3. -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 IP

    What each part does

    1. popods
    2. -o wideadd the pod IP, the node it runs on and nominated node
    3. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl get svc -n <namespace>List services

    What each part does

    1. svcshort name for services: TYPE, CLUSTER-IP, EXTERNAL-IP, PORT(S)
    2. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl get svc -o wide -n <namespace>List services with their selectors

    What each part does

    1. svc -o wideadd the SELECTOR column: which pod labels the service sends traffic to
    2. -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

    1. endpointslicesthe actual pod IPs:ports behind services (kubectl get ep <service> on older clusters)
    2. -l kubernetes.io/service-name=<service>only the slices of this service
    3. -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 deployments

    What each part does

    1. deploydeployments: READY (ready/desired), UP-TO-DATE, AVAILABLE
    2. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl get rs -n <namespace>List ReplicaSets

    What each part does

    1. rsReplicaSets; old ones with 0 replicas are kept for rollbacks
    2. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl get sts,ds -n <namespace>List StatefulSets and DaemonSets

    What each part does

    1. stsStatefulSets
    2. dsDaemonSets: desired / current / ready per node
    3. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl get ing -AList ingresses

    What each part does

    1. ingingresses: class, hosts, address, ports
    2. -Aall namespaces
  • kubectl get cm,secret -n <namespace>List ConfigMaps and Secrets

    What each part does

    1. cmConfigMaps
    2. secretSecrets (values are not shown)
    3. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl get pv,pvc -AList volumes and claims

    What each part does

    1. pvPersistentVolumes (cluster-wide): capacity, status, claim
    2. pvcPersistentVolumeClaims: Bound / Pending
    3. -Aall namespaces for the claims
  • kubectl get scList storage classes

    What each part does

    1. scStorageClasses; (default) marks the one used when a PVC names none
  • kubectl get jobs,cj -n <namespace>List jobs and cronjobs

    What each part does

    1. jobsJobs: completions, duration
    2. cjCronJobs: schedule, last schedule, active
    3. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl get hpa -n <namespace>List autoscalers

    What each part does

    1. hpaHorizontalPodAutoscalers: target metric vs current, min/max/current replicas
    2. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl get sa -n <namespace>List service accounts

    What each part does

    1. saServiceAccounts
    2. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl get netpol -n <namespace>List network policies

    What each part does

    1. netpolNetworkPolicies and the pods they select
    2. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl get crdList custom resource types

    What each part does

    1. crdCustomResourceDefinitions installed by operators and add-ons
  • kubectl api-resources --sort-by=name -o wideEvery short name and resource type

    What each part does

    1. api-resourcesevery resource type: SHORTNAMES (po, svc, deploy...), API group, namespaced, verbs
    2. --sort-by=namealphabetical
    3. -o wideinclude supported verbs
  • kubectl get po -l 'env in (prod,staging),tier!=frontend'Pods by set-based label selector

    What each part does

    1. -l '...'label selector
    2. env in (prod,staging)label env is one of these
    3. tier!=frontendand tier is not frontend
  • kubectl get po -A -o wide --field-selector spec.nodeName=<node>Pods on a specific node

    What each part does

    1. -A -o wideall namespaces, with node column
    2. --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

    1. -o nameprint type/name per line, e.g. pod/api-7d9f, ready for xargs
    2. -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 cluster

    What each part does

    1. -o jsonpath='...'loop over pods and their containers, print each image
    2. | sort | uniq -ccount pods per image
  • kubectl get po -w -n <namespace>Watch resources change

    What each part does

    1. -wkeep printing changes (status, restarts) until Ctrl+C
    2. -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

    1. kubectl configwork with the kubeconfig file
    2. current-contextprint the active context (cluster + user + default namespace)
  • kubectl config get-contexts; kubectl config use-context <context>List contexts and switch

    What each part does

    1. get-contextsall contexts; * marks the active one
    2. use-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 context

    What each part does

    1. set-contextedit a context
    2. --currentthe active one
    3. --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 IP

    What each part does

    1. kubectl get podslist pods
    2. -A--all-namespaces
    3. -o wideextra columns: node, pod IP, nominated node
  • kubectl get pods -A | grep <name>Find a pod by name fragment

    What each part does

    1. kubectl get pods -Aall pods in all namespaces (columns: NAMESPACE NAME READY STATUS…)
    2. |pipe the table into grep
    3. grep <name>keep rows containing <name> (pod name, namespace or status like CrashLoopBackOff)
  • kubectl get pods -A --field-selector=status.phase!=RunningPods that are not Running

    What each part does

    1. --field-selectorfilter on object fields server-side
    2. status.phase!=Runningphase is anything except Running (Pending, Failed, Succeeded, Unknown)
  • kubectl get pods -l app=<app> --show-labelsPods with a label

    What each part does

    1. -l app=<app>--selector: label must match (use "!key" to exclude, key in (a,b) for sets)
    2. --show-labelsadd a LABELS column
  • kubectl get pods -n <namespace> --sort-by=.status.containerStatuses[0].restartCountRecently restarted pods, sorted

    What each part does

    1. --sort-by=<jsonpath>sort rows by a field of the object
    2. .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 names

    What each part does

    1. -o jsonpath=…print fields using a JSONPath template
    2. {.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 image

    What each part does

    1. -o custom-columns=…build your own table
    2. NAME:.metadata.namecolumn header : JSONPath of the value
    3. IMAGE:.spec.containers[*].imageimages of all containers
  • kubectl api-resourcesWhat resource types exist (and their short names)

    What each part does

    1. api-resourcesevery resource type with short name (po, svc, deploy…), API group and whether it is namespaced
  • kubectl explain deployment.spec.strategyDocs for a field

    What each part does

    1. explainbuilt-in documentation for resource fields
    2. deployment.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

    1. describe pod <pod>status, conditions, container states (Last State / Exit Code) and events at the bottom
    2. -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 last

    What each part does

    1. get eventscluster events (scheduling, pulls, kills, probe failures)
    2. --sort-by=.metadata.creationTimestampoldest → newest
  • kubectl events -n <namespace> --types=WarningOnly warning events

    What each part does

    1. kubectl eventsnewer events subcommand
    2. --types=Warningonly Warning-type events
  • kubectl logs -f <pod> -n <namespace> --tail=200Follow logs of a pod

    What each part does

    1. logs <pod>container's stdout/stderr
    2. -fstream new lines
    3. --tail=200start from the last 200 lines
  • kubectl logs <pod> -c <container> --previousLogs of the crashed (previous) container

    What each part does

    1. -c <container>pick a container in a multi-container pod
    2. --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 label

    What each part does

    1. -l app=<app>every pod matching the label
    2. --all-containersall containers in each pod
    3. --prefixprefix lines with pod/container name
    4. -ffollow
  • kubectl logs deploy/<deployment> --since=1h | grep -i errorGrep logs for errors

    What each part does

    1. deploy/<deployment>logs from one pod of the deployment
    2. --since=1honly the last hour
    3. | grep -i errorkeep lines with "error", any case
  • kubectl top pod -n <namespace> --sort-by=memory --containersCPU / memory usage

    What each part does

    1. top podlive usage (needs metrics-server)
    2. --sort-by=memoryhighest memory first (or cpu)
    3. --containersper container instead of per pod

Exec, port-forward, copy4

  • kubectl exec -it <pod> -n <namespace> -- shShell into a pod

    What each part does

    1. exec <pod>run a command in a container of the pod
    2. -itinteractive stdin + terminal
    3. --everything after this is the command, not kubectl flags
    4. shthe shell (bash if available)
  • kubectl port-forward svc/<service> <local-port>:<service-port> -n <namespace>Reach a service from your laptop

    What each part does

    1. port-forwardtunnel a local port into the cluster
    2. svc/<service>target a service (or pod/<pod>, deploy/<name>)
    3. <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 pod

    What each part does

    1. cpcopy files (needs tar inside the container)
    2. <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 pod

    What each part does

    1. debug <pod>add an ephemeral debug container
    2. -itinteractive terminal
    3. --image=busybox:1.36image with the tools you need
    4. --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 manifests

    What each part does

    1. diff -f <dir>show what would change on the server
    2. &&continue only if diff ran without error (diff exits 1 when there are changes; use ; instead if you want to apply anyway)
    3. 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 deploymentCaution

    What each part does

    1. set imageupdate container images → triggers a rolling update
    2. deployment/<deployment>which deployment
    3. <container>=<image>:<tag>container name in the pod spec = new image
  • kubectl rollout status deployment/<deployment> --timeout=5mWait for the rollout to finish

    What each part does

    1. rollout statuswatch progress until done or failed
    2. --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 rollbackCaution

    What each part does

    1. rollout historylist revisions
    2. rollout undogo back to the previous revision
    3. --to-revision=<n>or to a specific revision from the history
  • kubectl rollout restart deployment/<deployment> -n <namespace>Restart all pods of a deploymentCaution

    What each part does

    1. rollout restartrolling restart without changing the spec (picks up new ConfigMap/Secret values)
  • kubectl scale deployment/<deployment> --replicas=<n>Scale replicasCaution

    What each part does

    1. scaleset the desired replica count
    2. --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 anything

    What each part does

    1. create deploymentbuild a Deployment object
    2. --dry-run=clientdon't send it to the cluster
    3. -o yamlprint it as YAML
    4. > deploy.yamlsave to a file to edit and commit

Cleanup & nodes4

  • kubectl delete pods -n <namespace> --field-selector=status.phase=FailedDelete failed / evicted podsDestructive

    What each part does

    1. delete podsdelete pods…
    2. --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 patternDestructive

    What each part does

    1. --no-headersdrop the header row so only data lines go through
    2. awk '/<pattern>/{print $1}'for lines matching <pattern>, print column 1 (the pod name)
    3. 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 backCaution

    What each part does

    1. drain <node>cordon the node and evict its pods
    2. --ignore-daemonsetsdon't fail on DaemonSet pods (they stay)
    3. --delete-emptydir-dataallow evicting pods that use emptyDir (that data is lost)
    4. uncordon <node>make it schedulable again
  • kubectl top node; kubectl describe node <node>Node usage and details

    What each part does

    1. top nodeCPU/memory per node
    2. describe nodecapacity, allocatable, conditions (DiskPressure, MemoryPressure) and pods on it

Services, DNS & networking checks6

  • kubectl describe svc <service> -n <namespace>Describe a service

    What each part does

    1. describe svctype, selector, ports, target ports, endpoints and events
    2. -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 cluster

    What each part does

    1. kubectl run dnstest --rm -it --restart=Neverthrowaway pod, removed when done
    2. --image=busybox:1.36small image with nslookup
    3. <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 cluster

    What each part does

    1. --image=curlimages/curlimage with curl
    2. http://<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 pod

    What each part does

    1. deploy/<deployment>picks one pod of the deployment (also pod/<pod>, svc/<service>)
    2. <local-port>:<container-port>localhost port : port in the pod
    3. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl proxy --port=8001Open a local proxy to the API server

    What each part does

    1. kubectl proxyauthenticated proxy: http://localhost:8001/api/... reaches the API, and services via /api/v1/namespaces/<ns>/services/<svc>/proxy/
    2. --port=8001local port
  • kubectl get --raw='/readyz?verbose'Check the API server health

    What each part does

    1. get --rawcall an API path directly
    2. /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 pod

    What each part does

    1. kubectl exec <pod>run in the pod (add -c <container>)
    2. -n <namespace>in this namespace (default: the context's namespace; -A for all)
    3. -- 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

    1. set env ... --listlist the env defined in the pod template, showing which come from configMapKeyRef / secretKeyRef
    2. -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)Caution

    What each part does

    1. <KEY>=<value>add or change
    2. <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 file

    What each part does

    1. create configmap <name>new ConfigMap
    2. --from-literal=<key>=<value>one key/value
    3. --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 secret

    What each part does

    1. secret genericOpaque secret
    2. --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 secret

    What each part does

    1. 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 secret

    What each part does

    1. secret tlskubernetes.io/tls secret used by ingresses
    2. --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 secret

    What each part does

    1. -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

    1. --dry-run=client -o yamlgenerate the manifest without creating
    2. | 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 manifest

    What each part does

    1. kubectl run <name> --image=<image>a single pod (the old --generator flag is gone)
    2. --dry-run=client -o yamlprint YAML instead of creating
    3. > pod.yamlsave to edit
  • kubectl expose deploy <deployment> --port=<port> --target-port=<container-port> --dry-run=client -o yaml > svc.yamlGenerate a service manifest

    What each part does

    1. expose deploy <deployment>service selecting the deployment's pods
    2. --port / --target-portservice port / container port
    3. --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

    1. create job --from=cronjob/<cronjob>one-off Job using the CronJob's template
    2. -n <namespace>in this namespace (default: the context's namespace; -A for all)
  • kubectl create cronjob <name> --image=<image> --schedule='*/5 * * * *' -- <command>Create a cronjob

    What each part does

    1. --schedule='...'cron schedule
    2. -- <command>what the container runs
  • kubectl get deploy <deployment> -n <namespace> -o yaml > deploy.yamlExport an existing object as clean YAML

    What each part does

    1. -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 recursively

    What each part does

    1. -Rrecurse into subdirectories
    2. -f <dir>every manifest in it
  • kubectl apply -k <overlay-dir>Apply a Kustomize overlay

    What each part does

    1. -k <dir>render kustomization.yaml and apply; kubectl kustomize <dir> just prints it
  • kubectl apply --server-side -f <file>Server-side apply

    What each part does

    1. --server-sidethe API server merges and tracks field ownership; needed for large CRDs
  • kubectl replace --force -f <file>Replace an object (delete + recreate)Caution

    What each part does

    1. 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 ready

    What each part does

    1. kubectl wait --for=condition=Readyblock until the condition is true (also --for=delete, --for=jsonpath=...)
    2. pod -l app=<app>which objects
    3. --timeout=120sfail after 2 minutes

Patch, label, annotate & scale9

  • kubectl patch deploy <deployment> -n <namespace> -p '{"spec":{"replicas":3}}'Patch a field (strategic merge)Caution

    What each part does

    1. patchchange part of a live object without a full manifest
    2. -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 patchCaution

    What each part does

    1. --type=jsonRFC 6902 operations: add, remove, replace at a path
    2. -p '[...]'the operations
  • kubectl label po <pod> <key>=<value>; kubectl label po <pod> <key>-Add / remove a label

    What each part does

    1. <key>=<value>add (add --overwrite to change)
    2. <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 annotation

    What each part does

    1. annotatenon-identifying metadata read by tools
    2. --overwritereplace an existing value
  • kubectl autoscale deploy <deployment> --min=2 --max=10 --cpu-percent=80Autoscale a deployment

    What each part does

    1. autoscalecreate an HPA
    2. --min / --maxreplica bounds
    3. --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 limitsCaution

    What each part does

    1. set resourceschange resources in the pod template (rollout follows)
    2. --requests / --limitsvalues per container
  • kubectl rollout pause deploy/<deployment>; kubectl rollout resume deploy/<deployment>Pause and resume a rollout

    What each part does

    1. rollout pausestop rolling out; batch several changes
    2. rollout resumeroll them out together
  • kubectl rollout history deploy/<deployment> --revision=<n>Details of one rollout revision

    What each part does

    1. --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 StatefulSet

    What each part does

    1. 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)Caution

    What each part does

    1. delete po <pod>graceful delete; a Deployment/StatefulSet makes a new one
    2. -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 podDestructive

    What each part does

    1. --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 labelDestructive

    What each part does

    1. po,svcseveral types at once
    2. -l app=<app>everything with that label
  • kubectl delete <type> <name> -n <namespace>Delete a resource by type and nameDestructive

    What each part does

    1. <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)Destructive

    What each part does

    1. allpods, services, deployments, replicasets, statefulsets, jobs (not configmaps, secrets, PVCs)
    2. --allevery object of those types
  • kubectl delete ns <namespace>Delete a namespace and everything in itDestructive

    What each part does

    1. 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 node

    What each part does

    1. 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 taint

    What each part does

    1. <key>=<value>:NoScheduleonly pods tolerating this taint can schedule here (NoExecute also evicts)
    2. <key>:NoSchedule-trailing minus removes it
  • kubectl label node <node> <key>=<value>Label a node

    What each part does

    1. label nodeused by nodeSelector / affinity, e.g. disktype=ssd
  • kubectl get nodes --show-labels; kubectl describe node <node> | grep -A3 TaintsNode labels and taints

    What each part does

    1. --show-labelsall labels (zone, instance type, OS, arch)
    2. 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

    1. 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

    1. auth can-iyes/no for an action, e.g. can-i delete pods
    2. --as=<user-or-sa>impersonate, e.g. system:serviceaccount:<ns>:<sa>
  • kubectl auth can-i --list -n <namespace>Everything I am allowed to do

    What each part does

    1. --listall verbs per resource for the current user in that namespace
  • kubectl auth whoamiWho am I logged in as?

    What each part does

    1. 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 account

    What each part does

    1. create tokenrequest a bound token (no long-lived secret)
    2. --duration=1hlifetime
  • kubectl get csr; kubectl certificate approve <csr>Approve a certificate signing requestCaution

    What each part does

    1. get csrpending node / user certificate requests
    2. certificate approvesign it
  • kubectl versionClient and server versions

    What each part does

    1. 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

    1. alias k=kubectltype k get po instead of kubectl get pods
    2. kubectl completion bashtab completion for resources and names (zsh: completion zsh)
    3. 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 kubeconfig

    What each part does

    1. get-clusterscluster entries
    2. get-userscredential entries
  • kubectl config view --minifyShow the current context's config only

    What each part does

    1. config viewkubeconfig contents (secrets redacted)
    2. --minifyonly what the current context uses
  • KUBECONFIG=~/.kube/config:<other-config> kubectl config view --flatten > merged-configMerge several kubeconfig files

    What each part does

    1. KUBECONFIG=a:bcolon-separated list of files kubectl reads together
    2. view --flattenone self-contained file
  • kubectl config delete-context <context>Remove a context

    What each part does

    1. delete-contextremove it from kubeconfig (cluster and user entries stay)
  • kubectx <context>; kubens <namespace>Switch context / namespace quickly

    What each part does

    1. kubectxswitch context (plugin)
    2. kubensswitch default namespace
  • kubectl explain pod.spec.containers --recursive | lessExplain every field of a resource

    What each part does

    1. explain <path>docs for a field
    2. --recursivethe whole tree of sub-fields
  • kubectl get po -A --sort-by=.metadata.creationTimestampSort output

    What each part does

    1. --sort-by=<jsonpath>sort by any field: creation time, .status.startTime, restartCount...
  • kubectl plugin list; kubectl krew listList kubectl plugins

    What each part does

    1. plugin listkubectl-* binaries on your PATH
    2. krew listplugins installed with the krew plugin manager
  • kubectl attach -it <pod> -c <container>Attach to a running container

    What each part does

    1. attachconnect to the main process's stdin/stdout (exec starts a new process instead)
  • kubectl get po -v=6Show more detail about what kubectl does

    What each part does

    1. -v=6log the API calls kubectl makes (8 includes bodies): useful for auth and timeout problems

My DevOps Playbook by Angelo John Calleja

New runbook

GitHub not connected

Saving is handled by the site: the GitHub token is stored in Cloudflare, not in your browser. Enter the editor password (the EDITOR_PASSWORD secret) to unlock saving in this browser.

Saving commits to gelogrammer/My_DevOps_Playbook. Create a fine-grained token with access to only this repo andContents: Read and write, then paste it here. It is stored only in this browser.

src/content/docs/…