Menu
CoddyTech

Kubernetes Cheat Sheet

Last updated

Contexts and cluster info

A context is a cluster, a user and a default namespace, stored in ~/.kube/config.

What it doesCommand
Show the client and server versionskubectl version
Show the cluster's addresseskubectl cluster-info
List contextskubectl config get-contexts
Show the current contextkubectl config current-context
Switch to another contextkubectl config use-context prod
Set the default namespace for this contextkubectl config set-context --current --namespace=dev
Show the merged kubeconfigkubectl config view
List the nodeskubectl get nodes
List every resource type and its short namekubectl api-resources
Explain a field of a resourcekubectl explain deployment.spec.replicas

Listing resources

kubectl get lists resources of a type. Add -n for another namespace.

What it doesCommand
List pods in the current namespacekubectl get pods
List pods in every namespacekubectl get pods -A
List pods in one namespacekubectl get pods -n kube-system
Add node and IP columnskubectl get pods -o wide
Show the labelskubectl get pods --show-labels
Filter by labelkubectl get pods -l app=web
Filter by fieldkubectl get pods --field-selector status.phase=Running
Keep watching for changeskubectl get pods -w
List deployments, services and pods togetherkubectl get deploy,svc,pods
List the common resourceskubectl get all
Show one resource as YAMLkubectl get deployment web -o yaml
List serviceskubectl get svc
List namespaceskubectl get ns
List recent events, oldest firstkubectl get events --sort-by=.metadata.creationTimestamp

Describe, logs and exec

Where to look when a pod is not Running.

What it doesCommand
Show a pod's details and eventskubectl describe pod web-7d4b9c8f6-x2k8p
Describe a deploymentkubectl describe deployment web
Show a pod's logskubectl logs web-7d4b9c8f6-x2k8p
Follow the logskubectl logs -f web-7d4b9c8f6-x2k8p
Logs of the container before it restartedkubectl logs --previous web-7d4b9c8f6-x2k8p
Logs of one container in the podkubectl logs web-7d4b9c8f6-x2k8p -c sidecar
Logs of a deployment's podskubectl logs deployment/web
Logs of every pod with a labelkubectl logs -l app=web --tail=50
Open a shell in a podkubectl exec -it web-7d4b9c8f6-x2k8p -- sh
Run one command in a podkubectl exec web-7d4b9c8f6-x2k8p -- env
Forward local port 8080 to a pod's port 80kubectl port-forward pod/web-7d4b9c8f6-x2k8p 8080:80
Forward to a servicekubectl port-forward svc/web 8080:80
Copy a file out of a podkubectl cp web-7d4b9c8f6-x2k8p:/etc/nginx/nginx.conf ./nginx.conf
Show CPU and memory use (needs metrics-server)kubectl top pods
Start a throwaway pod with a shellkubectl run tmp --rm -it --image=busybox -- sh

Creating and applying

apply creates a resource or updates it to match the file; it is the command to use with manifests in Git.

What it doesCommand
Create or update from a filekubectl apply -f deployment.yaml
Apply every file in a folderkubectl apply -f k8s/
Apply a kustomization folderkubectl apply -k overlays/prod
Show what apply would changekubectl diff -f deployment.yaml
Create a deploymentkubectl create deployment web --image=nginx --replicas=3
Start a single podkubectl run web --image=nginx
Expose a deployment as a servicekubectl expose deployment web --port=80 --target-port=8080
Expose it on a port of every nodekubectl expose deployment web --type=NodePort --port=80
Create a ConfigMap from valueskubectl create configmap app-config --from-literal=LOG_LEVEL=debug
Create a Secret from valueskubectl create secret generic db-pass --from-literal=password=s3cret
Create a ConfigMap from a filekubectl create configmap nginx-conf --from-file=nginx.conf
Write YAML for a deployment without creating itkubectl create deployment web --image=nginx --dry-run=client -o yaml > web.yaml
Run a Job oncekubectl create job hello --image=busybox -- echo hello
Edit a live resource in your editorkubectl edit deployment web

Deployments and rollouts

What it doesCommand
Scale to 5 replicaskubectl scale deployment web --replicas=5
Change the image (starts a rollout)kubectl set image deployment/web nginx=nginx:1.27
Watch a rollout until it finisheskubectl rollout status deployment/web
Show the rollout historykubectl rollout history deployment/web
Roll back to the previous versionkubectl rollout undo deployment/web
Roll back to a specific revisionkubectl rollout undo deployment/web --to-revision=2
Restart every pod of a deploymentkubectl rollout restart deployment/web
Pause a rolloutkubectl rollout pause deployment/web
Resume itkubectl rollout resume deployment/web
Autoscale on CPU usekubectl autoscale deployment web --min=2 --max=10 --cpu-percent=70
Set an environment variablekubectl set env deployment/web LOG_LEVEL=debug
Set CPU and memory requestskubectl set resources deployment web --requests=cpu=100m,memory=128Mi

Deleting

A deployment recreates any pod you delete; delete the deployment to remove its pods for good.

What it doesCommand
Delete what a file createdkubectl delete -f deployment.yaml
Delete a podkubectl delete pod web-7d4b9c8f6-x2k8p
Delete a deployment and its podskubectl delete deployment web
Delete pods by labelkubectl delete pods -l app=web
Delete a pod at once, without waitingkubectl delete pod web-7d4b9c8f6-x2k8p --grace-period=0 --force
Delete a namespace and everything in itkubectl delete namespace dev

Namespaces

What it doesCommand
List namespaceskubectl get namespaces
Create a namespacekubectl create namespace dev
Run any command in a namespacekubectl get pods -n dev
Make it the default for this contextkubectl config set-context --current --namespace=dev
Show the current context's namespacekubectl config view --minify -o jsonpath='{..namespace}'

Labels and annotations

What it doesCommand
Add a labelkubectl label pods web-7d4b9c8f6-x2k8p tier=frontend
Change a labelkubectl label pods web-7d4b9c8f6-x2k8p tier=backend --overwrite
Remove a labelkubectl label pods web-7d4b9c8f6-x2k8p tier-
Add an annotationkubectl annotate deployment web owner=team-a
Patch a fieldkubectl patch deployment web -p '{"spec":{"replicas":2}}'

Nodes

What it doesCommand
List nodes with their IPs and OSkubectl get nodes -o wide
Show a node's capacity, conditions and podskubectl describe node worker-1
Stop new pods landing on a nodekubectl cordon worker-1
Move pods off a node before maintenancekubectl drain worker-1 --ignore-daemonsets --delete-emptydir-data
Allow pods on the node againkubectl uncordon worker-1
Add a taintkubectl taint nodes worker-1 gpu=true:NoSchedule
Remove the taintkubectl taint nodes worker-1 gpu=true:NoSchedule-
Show node CPU and memory use (needs metrics-server)kubectl top nodes

Output formats

Add -o to any get to change what it prints.

What it doesCommand
Full object as YAMLkubectl get pod web-7d4b9c8f6-x2k8p -o yaml
Full object as JSONkubectl get pod web-7d4b9c8f6-x2k8p -o json
Names only (type/name)kubectl get pods -o name
Pick fields with JSONPathkubectl get pods -o jsonpath='{.items[*].metadata.name}'
Your own columnskubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName
Sort by a fieldkubectl get pods --sort-by=.status.startTime
Decode a Secret's valuekubectl get secret db-pass -o jsonpath='{.data.password}' | base64 -d

Short names

Most resource types have a short name you can type instead.

ResourceShort name
Podspo
Deploymentsdeploy
ReplicaSetsrs
StatefulSetssts
DaemonSetsds
Servicessvc
Ingressesing
ConfigMapscm
Namespacesns
Nodesno
PersistentVolumeClaimspvc
PersistentVolumespv
ServiceAccountssa
HorizontalPodAutoscalershpa
CronJobscj

Every kubectl command you reach for when working with Kubernetes (k8s), in copy-paste tables: contexts and namespaces first, then listing and describing resources, logs and exec, applying manifests, deployments and rollouts, scaling, labels, nodes and output formats.

kubectl talks to whichever cluster your current context points at, so check kubectl config current-context before you delete anything. To try the commands without a cluster, open the terminal playground, which has a single-node Kubernetes simulator built in.

kubectl cheat sheet FAQ

What is kubectl?
kubectl is the command-line client for Kubernetes. It sends your commands to a cluster's API server: kubectl get pods lists pods, kubectl apply -f creates or updates resources from YAML, kubectl logs and kubectl exec look inside running containers. Which cluster it talks to is set by the current context in ~/.kube/config.
Are k8s and Kubernetes the same thing?

Yes. k8s is short for Kubernetes: a k, the 8 letters in the middle, and an s. A k8s cheat sheet is a kubectl cheat sheet, because kubectl is how you work with a cluster.

What is the difference between kubectl apply and kubectl create?
kubectl create makes a resource and fails if it already exists. kubectl apply creates it or updates it to match your file, so you can run it again after every change. Use apply for manifests you keep in Git, and create for quick one-off resources.
How do I see why a pod is not starting?
Run kubectl describe pod <name> and read the Events at the bottom: image pull errors, failed scheduling and failing probes show up there. If the container started and crashed, kubectl logs --previous <name> shows the output of the run that crashed.
How do I switch namespaces in kubectl?
Add -n dev to a single command, or make dev the default for your current context with kubectl config set-context --current --namespace=dev.
How do I restart a deployment?
kubectl rollout restart deployment/web replaces every pod with a new one, a few at a time, with no downtime when there is more than one replica. kubectl rollout status deployment/web waits until it finishes.
Can I practice kubectl commands online?
Yes. The terminal playground has a single-node Kubernetes simulator: kubectl get, describe, apply, logs, exec, deployments, rollouts and services answer as on a real cluster, with nothing to install. A few commands, like port-forward and edit, need a real cluster such as kind or minikube.
Is this kubectl cheat sheet free?

Yes. It is free to read, copy and print, with no sign-up.

Coddy programming languages illustration

Learn Kubernetes with Coddy

Get started