kubectl cheat sheet
The kubectl commands you reach for every day, from switching context and reading a pod's logs to rolling back a Deployment and draining a node, checked on kubectl 1.36.
147 entries13 sectionsChecked on kubectl 1.36Reviewed
Names such as web, api, prod and node-1 are examples: put your own resource, namespace or node there. Every namespaced command takes -n <namespace>, or the context's default namespace when you leave it out; -A means every namespace. Many people alias k=kubectl; the code here spells it out.
Contexts and config
Which cluster, which user and which namespace each command goes to.
kubectl config current-contextPrint the context every command goes to now: a cluster, a user and a default namespace.
kubectl config get-contextsList the contexts in your kubeconfig; the current one is marked with
*.kubectl config use-context prodSwitch to the context
prodfor every later command.Warning: It is written to the kubeconfig file, so every other terminal that reads it switches too.
kubectl config set-context --current --namespace=webMake
webthe default namespace of the current context, so you can leave out-n web.kubectl --context staging -n api get podsRun one command against another context and namespace without switching.
Tip: Scripts should always pass
--context: they then never depend on what a person last switched to.kubectl config view --minifyShow only the current context's cluster, user and namespace, with credentials redacted.
Tip: Add
--rawto see the certificates and tokens as they are stored.KUBECONFIG=~/.kube/config:~/.kube/staging.yaml kubectl config view --flatten > merged.yamlMerge several kubeconfig files into one, with their certificates inlined.
kubectl config delete-context old-clusterRemove a context from the kubeconfig; its cluster and user entries stay until you delete them too.
kubectl versionPrint the versions of kubectl and of the cluster's API server.
Tip: kubectl is supported within one minor version of the API server, older or newer.
kubectl cluster-infoPrint the addresses of the control plane and of the cluster's core services, such as DNS.
Get and describe
List resources, pick the fields you need and read one in full.
kubectl get pods -o wideList pods with the node each runs on and its IP address.
kubectl get pods -AList pods in every namespace, with a column for the namespace.
kubectl get deploy,svc,ingress -n webList several kinds at once, separated by commas.
kubectl get pods -l 'app=api,tier!=cache'Select by labels:
=,!=, andin (a,b)ornotin (a,b)for sets.kubectl get pods -L app,versionAdd a column for each of the labels
appandversion.Tip:
--show-labelsprints every label in one column instead.kubectl get pods --field-selector status.phase!=RunningSelect by a field of the object, here every pod that is not running.
Warning: Only a few fields can be selected on, such as
metadata.name,status.phaseandspec.nodeName.kubectl get pod api-7d9f -o yamlPrint the whole object as the API server holds it, status included.
kubectl get deploy api -o jsonpath='{.spec.template.spec.containers[0].image}'Print one field with a JSONPath expression, here the image of the first container.
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\n"}{end}'Print one line per pod, its name and its IP, with
rangeover the list.kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,IMAGES:.spec.containers[*].imagePrint a table of the columns you name, each a header and a field's path.
kubectl get pods --sort-by=.metadata.creationTimestampSort the list by a field, here the oldest pod first.
kubectl get pods -wPrint the list, then a line for each change until you stop it with Ctrl+C.
kubectl describe pod api-7d9fRead a resource in full, in words: its containers, conditions, volumes and, at the foot, its recent events.
kubectl get all -n webList the common workload kinds in a namespace: pods, Services, Deployments, ReplicaSets, StatefulSets, Jobs.
Warning:
allis a fixed category: it leaves out ConfigMaps, Secrets, Ingresses, PersistentVolumeClaims and custom resources.kubectl api-resourcesList every kind the cluster serves, with its short name, API group and whether it is namespaced.
kubectl explain deployment.spec.strategy --recursiveRead the schema of a field from the cluster's own API, every field under it included.
Create and apply
Make resources from files, or generate their YAML to start from.
kubectl apply -f deploy.yamlCreate the resources in a file, or update them to match it if they exist.
kubectl apply -R -f k8s/Apply every manifest in a directory and the directories under it.
kubectl apply -k overlays/prodBuild a Kustomize directory and apply the result.
kubectl kustomize overlays/prodPrint what a Kustomize directory builds, without applying it.
kubectl diff -f deploy.yamlShow what applying the file would change in the cluster, as a diff.
Tip: It exits with 1 when there are differences and 0 when there are none, which a CI step can test.
kubectl apply -f deploy.yaml --dry-run=serverSend the change through the API server's validation and admission, without saving it.
kubectl apply --server-side -f deploy.yamlLet the API server merge the file and record which fields you own.
Tip: When another manager owns a field you set, the apply is refused;
--force-conflictstakes it over.kubectl create deployment api --image=ghcr.io/acme/api:1.4 --replicas=3 --dry-run=client -o yaml > deploy.yamlWrite a Deployment's YAML to start from, without sending anything to the cluster.
kubectl create namespace webCreate a namespace.
kubectl create job migrate --image=ghcr.io/acme/api:1.4 -- ./migrate upRun a command once to completion as a Job; what follows
--is the container's command.kubectl create cronjob backup --image=ghcr.io/acme/backup:2.1 --schedule='0 3 * * *' -- /backup.shRun a command on a cron schedule, here every day at 03:00 in the controller's time zone.
kubectl create job backup-now --from=cronjob/backupRun a CronJob's job now, once, without waiting for its schedule.
kubectl delete -f deploy.yamlDelete every resource the file names.
kubectl delete pod api-7d9f --grace-period=0 --forceRemove a pod's object at once, without waiting for its node to confirm the containers stopped.
Warning: Only for a pod stuck on a node that is gone: on a live node its containers may keep running beside the replacement.
Edit and patch
Change a live resource in place, from an editor or one command.
kubectl edit deploy apiOpen the live object in your editor; saving and closing applies the change.
Tip:
KUBE_EDITOR="code --wait"picks the editor; an editor that returns at once saves nothing.kubectl set image deploy/api api=ghcr.io/acme/api:1.5Change the image of the container
api, which starts a rollout.kubectl set env deploy/api LOG_LEVEL=debugSet an environment variable on every container of the Deployment;
LOG_LEVEL-removes it.kubectl set env deploy/api --listList the environment variables the Deployment's containers are given.
kubectl set resources deploy/api -c api --requests=cpu=250m,memory=256Mi --limits=memory=512MiSet the requests and limits of the container
api.kubectl patch deploy api -p '{"spec":{"replicas":5}}'Change fields with a strategic merge patch, the default: lists of containers merge by name.
kubectl patch svc api --type=merge -p '{"spec":{"type":"NodePort"}}'Change fields with a JSON merge patch, which replaces a list whole.
kubectl patch deploy api --type=json -p '[{"op":"remove","path":"/spec/template/spec/containers/0/args"}]'Change fields with a JSON patch: operations on paths, which can remove a field.
kubectl label pod api-7d9f env=prod --overwriteAdd or change a label;
env-in place ofenv=prodremoves it.kubectl annotate deploy api team=payments --overwriteAdd or change an annotation, which tools read and selectors do not.
kubectl replace --force -f pod.yamlDelete the resource and create it again from the file, for a field that cannot change in place.
Warning: Between the delete and the create the resource does not exist: a pod's work stops.
Deployments and rollouts
Roll out a new version, watch it, scale it and roll it back.
kubectl rollout status deploy/api --timeout=5mWait until the rollout is done, and exit with an error if it is not within five minutes.
Tip: Put it after the apply in a deploy job, so a rollout that never becomes ready fails the job.
kubectl rollout history deploy/apiList the Deployment's revisions, each a ReplicaSet it kept.
kubectl rollout history deploy/api --revision=3Show the pod template of revision 3.
kubectl annotate deploy/api kubernetes.io/change-cause='image 1.5, fix login'Set the line the history shows in
CHANGE-CAUSEfor the current revision.kubectl rollout undo deploy/apiRoll back to the revision before the current one.
kubectl rollout undo deploy/api --to-revision=3Roll back to revision 3 of the history.
kubectl rollout restart deploy/apiReplace every pod with a new one, by the rollout's rules, without changing the spec.
Tip: It works on StatefulSets and DaemonSets too:
kubectl rollout restart statefulset/db.kubectl rollout pause deploy/apiStop the Deployment from rolling out, so several changes go out as one;
rollout resumelets it.kubectl scale deploy/api --replicas=5Set the number of pods.
kubectl scale deploy/api --current-replicas=2 --replicas=3Scale only if the count is still 2, so two people do not overwrite each other.
kubectl autoscale deploy/api --min=2 --max=10 --cpu=70%Create a HorizontalPodAutoscaler that keeps average CPU near 70% of what the pods request.
Warning: It needs the metrics-server, and containers with a CPU request: a percentage is of the request.
kubectl get rs -l app=apiList the Deployment's ReplicaSets: the current one and the old ones a rollback goes to.
Logs, exec and debug
Read what a pod prints, open a shell in it, or debug it from beside it.
kubectl logs api-7d9fPrint what the pod's container has written to its standard output and error.
kubectl logs -f deploy/apiFollow the logs of one pod of the Deployment, picked for you.
Tip:
--all-podsreads every pod of it, each line prefixed with the pod's name.kubectl logs api-7d9f -c sidecarRead one container of a pod that has several; without
-cyou get the default one.kubectl logs api-7d9f --previousRead the logs of the container's last run, the one that crashed before this restart.
kubectl logs api-7d9f --since=15m --timestampsRead only the last 15 minutes, each line with the time it was written.
kubectl logs -l app=api --all-containers --prefix --tail=100Read the last 100 lines of every container of every pod with the label, each line prefixed with its source.
kubectl exec -it api-7d9f -- shOpen a shell in the pod's container; what follows
--is the command to run.kubectl exec api-7d9f -c api -- envRun one command in a given container and print what it prints.
kubectl exec -it deploy/api -- shOpen a shell in one pod of the Deployment, without looking up a pod's name.
kubectl debug -it api-7d9f --image=busybox:1.37 --target=apiAdd a debug container to the running pod, sharing the processes of its container
api.Tip: For an image with no shell: the debug container brings the tools, and
/proc/1/rootshows the target's files.kubectl debug api-7d9f -it --copy-to=api-debug --container=api -- shStart a copy of the pod with the command of its container
apireplaced by a shell, for one that crashes at start.kubectl debug node/node-1 -it --image=busybox:1.37Start a pod on a node in its host namespaces, with the node's file system at
/host.Warning: The pod stays after you exit: delete it with
kubectl delete podand the name the command printed.kubectl cp api-7d9f:/app/dump.json ./dump.jsonCopy a file out of a pod; swap the two arguments to copy one in.
Warning: It runs
tarin the container, so it fails on an image that has none.kubectl run tmp --rm -it --image=busybox:1.37 --restart=Never -- shStart a throwaway pod with a shell, which is deleted when you exit.
Services and networking
Expose a workload, reach it from your machine and check its endpoints.
kubectl expose deploy api --port=80 --target-port=8080Create a ClusterIP Service named
apithat sends its port 80 to the pods' port 8080.kubectl expose deploy api --name=api-public --type=LoadBalancer --port=80 --target-port=8080Create a Service that asks the cloud for an external load balancer.
kubectl get svc api -o jsonpath='{.status.loadBalancer.ingress[0].ip}'Print the external address a LoadBalancer Service was given.
Tip: Some clouds give a name, not an address: read
.hostnamein place of.ip.kubectl port-forward svc/api 8080:80Reach the Service's port 80 at
localhost:8080while the command runs.Warning: It picks one pod behind the Service and forwards to it alone: there is no load balancing.
kubectl port-forward deploy/db 15432:5432Reach a pod of the Deployment's port 5432 at
localhost:15432, such as a database.kubectl port-forward --address 0.0.0.0 svc/api 8080:80Listen on every interface of your machine, not only on localhost.
Warning: Anyone who can reach your machine then reaches the Service.
kubectl get endpointslices -l kubernetes.io/service-name=apiList the pod addresses behind the Service
api.Tip: No address means the Service's selector matches no ready pod: compare it with the pods' labels.
kubectl run dns-test --rm -it --image=busybox:1.37 --restart=Never -- nslookup api.web.svc.cluster.localCheck from inside the cluster that a Service's name resolves.
kubectl run http-test --rm -it --image=busybox:1.37 --restart=Never -- wget -qO- http://api.web/healthzCall a Service by its name from a throwaway pod, as another pod would.
kubectl get ingress -AList every Ingress, with its hosts and the address it was given.
kubectl get networkpolicy -n webList the NetworkPolicies of a namespace, which can explain traffic that never arrives.
kubectl proxy --port=8001Serve the API server at
localhost:8001with your credentials, forcurlor a browser.
ConfigMaps and Secrets
Configuration and credentials, from literals, files and env files.
kubectl create configmap api-config --from-literal=LOG_LEVEL=info --from-literal=REGION=eu-west-1Create a ConfigMap from keys and values given on the command line.
kubectl create configmap nginx-conf --from-file=nginx.confCreate a ConfigMap from a file, with the file's name as its key.
Tip:
--from-file=default.conf=./nginx.confgives the key another name; a directory adds each file in it.kubectl create configmap api-env --from-env-file=api.envCreate a ConfigMap from a file of
KEY=valuelines, one key per line.kubectl create configmap api-config --from-file=config/ --dry-run=client -o yaml | kubectl apply -f -Create a ConfigMap from files, or update it if it exists, which
createalone refuses.Warning: A pod that reads it as environment variables sees the change only once it restarts.
kubectl create secret generic db-creds --from-file=username=./username.txt --from-file=password=./password.txtCreate a Secret from files, so the values stay out of your shell's history.
kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -dPrint one value of a Secret, decoded from the base64 it is stored in.
kubectl get secret db-creds -o go-template='{{range $k, $v := .data}}{{$k}}={{$v | base64decode}}{{"\n"}}{{end}}'Print every key of a Secret with its decoded value, one per line.
kubectl create secret tls api-tls --cert=tls.crt --key=tls.keyCreate a TLS Secret from a certificate and its key, for an Ingress to use.
kubectl create secret docker-registry ghcr --docker-server=ghcr.io --docker-username=acme --docker-password="$GHCR_TOKEN"Create the Secret a pod names in
imagePullSecretsto pull from a private registry.kubectl patch serviceaccount default -p '{"imagePullSecrets":[{"name":"ghcr"}]}'Give every pod that runs as the namespace's
defaultservice account the registry Secret.
Nodes and scheduling
Take a node out of service, put it back, and steer where pods land.
kubectl get nodes -o wideList the nodes with their roles, version, addresses, OS image and container runtime.
kubectl describe node node-1Read a node's conditions, capacity, taints and, under Allocated resources, what its pods request.
kubectl get pods -A --field-selector spec.nodeName=node-1List every pod that runs on one node.
kubectl cordon node-1Mark the node unschedulable: its pods keep running, and no new pod lands there.
kubectl drain node-1 --ignore-daemonsets --delete-emptydir-dataCordon the node and evict its pods, by their disruption budgets, before maintenance.
Warning:
--delete-emptydir-dataloses what pods kept inemptyDirvolumes: it is gone with the pod.Tip:
--timeout=10mstops waiting on an eviction that never comes, instead of hanging.kubectl uncordon node-1Let pods be scheduled on the node again after maintenance.
kubectl taint nodes node-1 dedicated=gpu:NoScheduleKeep off the node every pod that does not tolerate the taint;
dedicated=gpu:NoSchedule-removes it.kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints[*].keyList the keys of each node's taints.
kubectl label nodes node-1 disktype=ssdLabel a node, for a pod's
nodeSelectoror node affinity to choose it.kubectl top nodesShow each node's CPU and memory use now.
Warning:
kubectl topreads the metrics API: it needs the metrics-server, or it answers that the API is not available.kubectl top pods -A --sort-by=memoryShow every pod's CPU and memory use, the largest memory first.
kubectl top pod api-7d9f --containersShow the use of each container of a pod.
Access and RBAC
Who you are to the cluster, what you may do, and granting access.
kubectl auth whoamiPrint the user name and groups the API server sees for your credentials.
kubectl auth can-i create deployments -n webAsk whether you may do something; it answers
yesorno.kubectl auth can-i --list -n webList everything you may do in a namespace.
kubectl auth can-i get secrets -n web --as=system:serviceaccount:web:apiAsk the same for another identity, here the service account
apiofweb.Tip:
--asis impersonation: you need theimpersonatepermission yourself.kubectl create serviceaccount deployer -n webCreate an identity for a program, such as a CI job.
kubectl create role pod-reader --verb=get,list,watch --resource=pods,pods/log -n webCreate a Role that may read pods and their logs in one namespace.
kubectl create rolebinding deployer-pods --role=pod-reader --serviceaccount=web:deployer -n webGive the Role to a service account, written as
namespace:name.kubectl create rolebinding devs-view --clusterrole=view --group=devs -n webGive a group the built-in read-only role, in one namespace only.
Tip: The built-in roles are
view,edit,adminandcluster-admin;viewcannot read Secrets.kubectl create token deployer -n web --duration=1hPrint a short-lived token for a service account, to put in a kubeconfig or a CI secret.
Warning: The API server can give a shorter life than you ask for.
kubectl get rolebindings,clusterrolebindings -A -o wideList every binding with its role and the users, groups and service accounts it names.
Troubleshooting
Events, conditions and the cluster's own health checks.
kubectl events -n webList a namespace's recent events, the oldest first, such as failed scheduling, pulls and probe failures.
Tip: Events are kept for about an hour by default: look soon after the trouble.
kubectl events -n web --for pod/api-7d9fList only the events about one resource.
kubectl events -A --types=Warning -wWatch every warning in the cluster as it happens.
kubectl get pods -A --field-selector status.phase=PendingList the pods that are not scheduled or not started;
describeone to read why.kubectl get pod api-7d9f -o jsonpath='{.status.containerStatuses[*].lastState.terminated.reason}'Print why each container last stopped, such as
OOMKilledorError.kubectl wait --for=condition=Ready pod -l app=api --timeout=2mWait until every pod with the label is ready, or fail after two minutes.
kubectl wait --for=condition=complete job/migrate --timeout=10mWait until a Job has finished, as a step before the next one.
kubectl wait --for=delete pod/api-7d9f --timeout=60sWait until a resource is gone after a delete.
kubectl get --raw='/readyz?verbose'Print each of the API server's readiness checks, with
okor why it failed.kubectl get pods -v=6Print the HTTP requests kubectl makes, with their status codes and timings.
Tip:
-v=8also prints the bodies; mind what it shows before you paste it anywhere.
Manifests
YAML to start from, generated or written by hand.
deploy.yaml
apiVersion: apps/v1 kind: Deployment metadata: name: api labels: app: api spec: replicas: 3 selector: matchLabels: app: api template: metadata: labels: app: api spec: containers: - name: api image: ghcr.io/acme/api:1.4 ports: - containerPort: 8080 resources: requests: cpu: 250m memory: 256Mi limits: memory: 512Mi readinessProbe: httpGet: path: /healthz port: 8080 --- apiVersion: v1 kind: Service metadata: name: api spec: selector: app: api ports: - port: 80 targetPort: 8080A Deployment and the Service in front of it: requests to schedule by, a memory limit, and a probe that keeps an unready pod out of the Service.
Warning:
spec.selectorcannot change once the Deployment exists, and must match the template's labels.kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization namespace: web resources: - ../../base images: - name: ghcr.io/acme/api newTag: "1.5" patches: - target: kind: Deployment name: api patch: |- - op: replace path: /spec/replicas value: 5An overlay for
kubectl apply -k: the base's resources in another namespace, with another image tag and replica count.kubectl create deployment api --image=ghcr.io/acme/api:1.4 --port=8080 --dry-run=client -o yamlPrint a Deployment to start a manifest from;
create service,create joband the others do the same.kubectl get deploy api -o yaml --show-managed-fields=false > api.yamlSave a live resource as YAML, without the bookkeeping of which manager set each field.
Tip: Before you apply it elsewhere, remove
status,uid,resourceVersionandcreationTimestamp.
Pitfalls
What goes wrong with kubectl, and how to get out of it.
A command changed the wrong cluster: the terminal was still on the context of the day before.
Fix:
use-contextis written to the kubeconfig file and holds in every shell. Pass--contextin scripts, show the current context in your prompt, or keep production in a kubeconfig of its own that you name withKUBECONFIG.A pod is in
CrashLoopBackOffandkubectl logsshows nothing, or only the start of a run.Fix: Read the run that crashed with
kubectl logs --previous, andkubectl describe podfor its last state: exit code 137 is a kill, oftenOOMKilled; 1 is the app's own error.A pod stays in
ImagePullBackOfforErrImagePull.Fix:
kubectl describe podsays why at the foot: a tag that does not exist, a registry that refused, or a private image with no pull Secret. Create one withcreate secret docker-registryand name it inimagePullSecrets.A pod stays
Pendingand never starts.Fix: Its events say why: no node has the CPU or memory it requests, a taint it does not tolerate, a
nodeSelectorno node matches, or a PersistentVolumeClaim that is not bound. Lower the requests, or fix what the event names.kubectl drainrepeats "Cannot evict pod as it would violate the pod's disruption budget" and never ends.Fix: A PodDisruptionBudget allows no pod to go, as when
minAvailableequals the replicas. Scale the workload up or relax the budget for the maintenance;--disable-evictionskips budgets and is the last resort.A change made with
kubectl edit podis gone a few minutes later.Fix: A pod of a Deployment is replaced from its template, which your edit did not touch. Change the Deployment (
kubectl edit deploy,set image,set env) and let it roll out.kubectl applyfails withfield is immutableon a Deployment'sspec.selector.Fix: A Deployment's selector cannot change after it is created. Create the Deployment under a new name and move the Service to it, or delete it and apply again, which stops its pods meanwhile.
kubectl applywarns that the resource is missing thelast-applied-configurationannotation.Fix: It was made with
createor by another tool. The apply adds the annotation and goes on; from then on, change it withapplyonly, or useapply --server-side, which needs no annotation.kubectl port-forwardstops withlost connection to pod.Fix: It forwards to one pod, picked when it starts, and ends when that pod goes, in a rollout or a restart. Start it again; for something that lasts, reach the Service through an Ingress or a LoadBalancer.
A Secret's values are taken to be safe because they look encrypted.
Fix:
datais base64, an encoding: anyone who mayget secretsreads them. Keep that permission narrow with RBAC, and turn on encryption at rest for etcd.A namespace stays in
Terminatinglong afterkubectl delete namespace.Fix: Something in it has a finalizer whose controller is gone.
kubectl get namespace web -o yamlnames it understatus.conditions; reinstall its controller, or, knowing what you lose, remove that resource's finalizer withkubectl patch.kubectl logs -f -l app=apirefuses: you are attempting to follow more log streams than the maximum allowed.Fix: It follows at most five at once by default. Raise it with
--max-log-requests=10, or narrow the selector.