Kubernetes Cheat Sheet
Every essential kubectl command and YAML manifest - searchable, organized, copy-ready.
kubectl cluster-info
kubectl version --short
kubectl get nodes
kubectl get nodes -o wide
kubectl describe node <node-name>
kubectl get all
kubectl get all --all-namespaces
kubectl get <resource> <name> -o yaml
kubectl get pods -w
kubectl api-resources
kubectl explain <resource>
kubectl explain pod.spec.containers
kubectl explain deployment.spec --recursive
kubectl apply -f manifest.yaml
kubectl apply -f ./k8s/
kubectl apply -f manifest.yaml --dry-run=client
kubectl delete -f manifest.yaml
kubectl delete pod <name> --grace-period=0 --force
kubectl label pod <name> env=production
kubectl label pod <name> env-
kubectl label pod <name> env=staging --overwrite
kubectl annotate pod <name> description="my pod"
kubectl annotate pod <name> description-
kubectl get pods -l app=myapp,env=prod
kubectl get pods
kubectl get pods -o wide
kubectl get pods --show-labels
kubectl describe pod <pod-name>
kubectl run tmp --image=busybox -it --rm -- sh
kubectl logs <pod-name>
kubectl logs -f <pod-name>
kubectl logs <pod-name> -c <container>
kubectl logs <pod-name> --previous
kubectl logs <pod-name> --tail=100
kubectl logs -l app=myapp --all-containers
kubectl exec -it <pod-name> -- /bin/sh
kubectl exec <pod-name> -- env
kubectl port-forward <pod-name> 8080:80
kubectl port-forward svc/<svc-name> 8080:80
kubectl cp <pod>:/path/to/file ./local-file
kubectl get deployments
kubectl create deployment <name> --image=nginx:1.25
kubectl scale deployment <name> --replicas=3
kubectl set image deployment/<name> <container>=nginx:1.26
kubectl autoscale deployment <name> --min=2 --max=10 --cpu-percent=80
kubectl rollout status deployment/<name>
kubectl rollout history deployment/<name>
kubectl rollout undo deployment/<name>
kubectl rollout undo deployment/<name> --to-revision=2
kubectl rollout restart deployment/<name>
kubectl get statefulsets
kubectl get daemonsets
kubectl get jobs
kubectl get cronjobs
kubectl get services
kubectl expose deployment <name> --port=80 --target-port=8080
kubectl expose deployment <name> --type=NodePort --port=80
kubectl expose deployment <name> --type=LoadBalancer --port=80
kubectl get endpoints
kubectl get ingress
kubectl describe ingress <name>
kubectl get networkpolicies
kubectl get configmaps
kubectl create configmap <name> --from-literal=key=value
kubectl create configmap <name> --from-file=config.env
kubectl create secret generic <name> --from-literal=password=s3cr3t
kubectl create secret docker-registry regcred \
--docker-server=<registry> \
--docker-username=<user> \
--docker-password=<pass>
kubectl get secret <name> -o jsonpath='{.data.password}' | base64 --decode
kubectl create secret tls <name> --cert=tls.crt --key=tls.key
kubectl get roles
kubectl get clusterroles
kubectl auth can-i --list
kubectl auth can-i create pods
kubectl get namespaces
kubectl create namespace <name>
kubectl get pods -n <namespace>
kubectl get pods -A
kubectl delete namespace <name>
kubectl config get-contexts
kubectl config current-context
kubectl config use-context <context-name>
kubectl config set-context --current --namespace=<ns>
kubectl get pv
kubectl get pvc
kubectl describe pvc <name>
kubectl get storageclass
kubectl cordon <node-name>
kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data
kubectl uncordon <node-name>
kubectl taint node <node-name> key=value:NoSchedule
kubectl taint node <node-name> key=value:NoExecute
kubectl taint node <node-name> key-
kubectl get node <node-name> -o jsonpath='{.spec.taints}'
kubectl get events --sort-by='.lastTimestamp'
kubectl get pods --field-selector=status.phase!=Running
kubectl top nodes
kubectl top pods --sort-by=cpu
kubectl get pods -o jsonpath='{.items[*].status.podIP}'
kubectl get pods -o custom-columns='NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName'
kubectl patch deployment <name> -p '{"spec":{"replicas":5}}'
kubectl edit deployment <name>
# pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: my-pod
labels:
app: my-pod
spec:
containers:
- name: main
image: nginx:1.25
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: app
image: my-image:latest
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
# service.yaml
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: ClusterIP
# ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
tls:
- hosts: [example.com]
secretName: my-tls-secret
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-service
port:
number: 80
# pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
accessModes:
- ReadWriteOnce
storageClassName: standard
resources:
requests:
storage: 5Gi
# hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
helm repo add <name> https://charts.example.com
helm repo update
helm search repo <keyword>
helm show values <repo/chart>
helm install <release-name> <repo/chart>
helm install <release-name> <repo/chart> -n <namespace> --create-namespace
helm install <release-name> <repo/chart> -f values.yaml
helm install <release-name> <repo/chart> --set replicaCount=2
helm upgrade <release-name> <repo/chart> -f values.yaml
helm upgrade --install <release-name> <repo/chart>
helm install <release-name> <repo/chart> --dry-run --debug
helm list -A
helm status <release-name>
helm history <release-name>
helm rollback <release-name> <revision>
helm uninstall <release-name>
helm template <release-name> <repo/chart>
This Kubernetes cheat sheet covers every kubectl command, YAML template, and Helm workflow you actually need, all in one searchable reference.
Keeping k8s syntax in your head is unrealistic. Clusters are complex, commands are verbose, and the official docs are extensive. This reference exists so you can stop searching and start shipping.
What's Inside
-
Basics - cluster info, resource listing, apply/delete, labels and annotations
-
Pods - list, describe, logs, exec, port-forward, file copy
-
Deployments - scale, update images, rollout history, rollback, restart
-
Services and Networking - ClusterIP, NodePort, LoadBalancer, Ingress, NetworkPolicies
-
Config and Secrets - ConfigMaps, Secrets, Docker registry credentials, TLS, RBAC
-
Namespaces and Context - switching contexts, setting defaults, merging kubeconfigs
-
Storage - PersistentVolumes, PersistentVolumeClaims, StorageClasses
-
Node Management - cordon, drain, uncordon, taints and tolerations
-
Debugging - events, resource usage, JSONPath queries, patching
-
YAML Templates - ready-to-paste manifests for Pod, Deployment, Service, Ingress, PVC, HPA
-
Helm - repo management, install, upgrade, rollback, dry-run, template rendering
How to Use It
Search any command with /. Every snippet is syntax-highlighted so flags, resource types, and placeholders are visually distinct. Destructive commands are clearly marked. One click copies the exact command.
Placeholders like <pod-name> are highlighted in amber. Replace them with your actual values before running.
Who It's For
Works for anyone touching a cluster regularly. Useful whether you are onboarding to Kubernetes for the first time or just need a fast lookup mid-deploy. The YAML Templates tab alone saves significant time on boilerplate.
What is a Kubernetes Cheat Sheet
A Kubernetes cheat sheet is a quick-reference guide that collects the most-used kubectl commands, YAML syntax patterns, and resource management rules into one place.
It covers pod lifecycle management, cluster configuration, debugging, scaling, and storage, so you don't have to dig through official docs every time you forget a flag.
Useful for developers shipping to GKE, EKS, or AKS, and for DevOps engineers managing multi-cluster environments.
How to Install and Configure kubectl
kubectl is the command-line tool for communicating with a Kubernetes cluster's control plane via the Kubernetes API.
Before running any kubectl commands, you need it installed and pointed at the right cluster.
How to Install kubectl on Linux, macOS, and Windows
All three platforms have stable install paths. No compilation needed.
Linux:
curl -LO "https://dl.k8s.io/release/$(curl -Ls https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl && sudo mv kubectl /usr/local/bin/
macOS (Homebrew):
brew install kubectl
Windows (Chocolatey):
choco install kubernetes-cli
Verify the install:
kubectl version --client
How to Set Up a kubeconfig File
kubectl reads cluster credentials and context from a kubeconfig file, located at ~/.kube/config by default.
Cloud providers auto-generate this file when you authenticate.
GKE:
gcloud container clusters get-credentials CLUSTER_NAME --region REGION
EKS:
aws eks update-kubeconfig --name CLUSTER_NAME --region REGION
How to Switch Between Kubernetes Contexts
Each context in a kubeconfig file maps to a cluster, user, and namespace combination.
List available contexts:
kubectl config get-contexts
Switch context:
kubectl config use-context CONTEXT_NAME
How to Merge Multiple kubeconfig Files
Set the KUBECONFIG environment variable to a colon-separated list of config file paths, then flatten:
export KUBECONFIG=~/.kube/config:~/.kube/config2
kubectl config view --flatten > ~/.kube/merged-config
How to Manage Kubernetes Clusters
How to Check Cluster Info and Component Status
Get the Kubernetes API server address and cluster services:
kubectl cluster-info
Check the health of core control plane components (API server, etcd, scheduler):
kubectl get componentstatuses
List all nodes with status and Kubernetes version:
kubectl get nodes -o wide
How to View and Set the Active Namespace
kubectl defaults to the default namespace unless configured otherwise.
Most production clusters use custom namespaces for namespace isolation between teams or environments.
View current namespace:
kubectl config view --minify | grep namespace
Set a persistent namespace for the active context:
kubectl config set-context --current --namespace=NAMESPACE_NAME
Pass -n to any command for a one-off override:
kubectl get pods -n kube-system
How to Work with Kubernetes Pods
How to Create, Run, and Delete Pods
You can create a pod directly with kubectl or apply a YAML manifest.
Direct creation works for quick testing. In real environments, use a deployment instead.
How to Run a Pod with a Specific Image
kubectl run POD_NAME --image=IMAGE_NAME:TAG
Add --rm and -it for an interactive shell that cleans up on exit:
kubectl run -it --rm debug --image=busybox -- sh
How to Delete a Pod Forcefully
Standard delete waits for graceful shutdown. Use --force and --grace-period=0 to skip the wait:
kubectl delete pod POD_NAME --force --grace-period=0
How to Get Pod Logs and Events
Logs and events are usually the first stop when debugging. kubectl gives you both.
How to Stream Logs from a Running Container
Follow live logs with -f, same as tail -f:
kubectl logs -f POD_NAME
For multi-container pods, specify the container:
kubectl logs -f POD_NAME -c CONTAINER_NAME
How to Get Logs from a Crashed Pod
Use --previous to see logs from the last terminated container instance.
Fastest way to debug a CrashLoopBackOff:
kubectl logs POD_NAME --previous
How to Execute Commands Inside a Pod
The kubectl exec command runs a command directly inside a running container, similar to docker exec.
Interactive shell:
kubectl exec -it POD_NAME -- /bin/bash
One-off command without an interactive session:
kubectl exec POD_NAME -- ls /app
How to Manage Kubernetes Deployments
How to Create and Apply a Deployment
A Kubernetes deployment manages a replica set and handles rolling updates automatically.
Imperative (quick testing):
kubectl create deployment DEPLOY_NAME --image=IMAGE_NAME:TAG
Declarative (production):
kubectl apply -f deployment.yaml
How to Scale a Deployment
The horizontal pod autoscaler can handle this automatically, but manual scaling is faster for urgent changes:
kubectl scale deployment DEPLOY_NAME --replicas=5
How to Update a Deployment Image
Trigger a rolling update by setting a new container image. Kubernetes replaces pods gradually, keeping the service available:
kubectl set image deployment/DEPLOY_NAME CONTAINER_NAME=NEW_IMAGE:TAG
Check rollout status:
kubectl rollout status deployment/DEPLOY_NAME
How to Roll Back a Deployment
How to Check Rollout History
Each kubectl apply or set image creates a new revision. View them:
kubectl rollout history deployment/DEPLOY_NAME
Inspect a specific revision:
kubectl rollout history deployment/DEPLOY_NAME --revision=2
How to Undo a Kubernetes Rollout
Roll back to the previous revision:
kubectl rollout undo deployment/DEPLOY_NAME
Roll back to a specific revision number:
kubectl rollout undo deployment/DEPLOY_NAME --to-revision=2
How to Work with Kubernetes Services
How to Expose a Deployment as a Service
kubectl expose deployment DEPLOY_NAME --port=80 --target-port=8080
Add --type=NodePort or --type=LoadBalancer to control external access.
Kubernetes Service Types: ClusterIP, NodePort, LoadBalancer
-
ClusterIP - internal only, no external access
-
NodePort - exposes on a static port on each node
-
LoadBalancer - provisions a cloud load balancer (GKE, EKS, AKS)
When to Use ClusterIP vs NodePort vs LoadBalancer
ClusterIP for internal microservice communication.
NodePort for quick external testing. LoadBalancer for production workloads that need a stable external IP.
How to Manage ConfigMaps and Secrets
How to Create a ConfigMap from a File or Literal
From a literal value:
kubectl create configmap CONFIG_NAME --from-literal=key=value
From a file:
kubectl create configmap CONFIG_NAME --from-file=config.properties
How to Create and Use a Kubernetes Secret
kubectl create secret generic SECRET_NAME --from-literal=password=mypassword
Kubernetes base64-encodes the value automatically. Don't store secrets in version control.
How to Mount a Secret as an Environment Variable
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: SECRET_NAME
key: password
How to Mount a Secret as a Volume
volumes:
- name: secret-vol
secret:
secretName: SECRET_NAME
Reference it in the container under volumeMounts with a mountPath.
How to Work with Namespaces
How to Create and Delete a Namespace
kubectl create namespace NAMESPACE_NAME
kubectl delete namespace NAMESPACE_NAME
Deleting a namespace removes all resources inside it. No confirmation prompt.
How to List Resources Across All Namespaces
Add --all-namespaces or -A to any kubectl get command:
kubectl get pods -A
kubectl get services -A
How to Manage Persistent Volumes and Storage
How to Create a PersistentVolume and PersistentVolumeClaim
A PersistentVolume (PV) is a cluster-level storage resource. A PersistentVolumeClaim (PVC) is how a pod requests storage.
Basic PVC:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
How to Check Storage Class and Volume Status
kubectl get storageclass
kubectl get pv
kubectl get pvc
Bound means the PVC is matched to a PV and ready to use. Pending means no matching PV exists yet.
How to Use Labels, Selectors, and Annotations
How to Add and Remove Labels from Resources
Add a label:
kubectl label pod POD_NAME env=production
Remove a label (note the - suffix):
kubectl label pod POD_NAME env-
How to Filter Resources by Label
Label selectors let you query resources by key-value pairs across any resource type.
kubectl get pods -l env=production
kubectl get pods -l 'env in (production, staging)'
How to Debug and Troubleshoot Kubernetes
How to Describe a Resource for Debugging
kubectl describe gives you events, conditions, resource limits, and mounted volumes - far more useful than kubectl get for diagnosing problems.
kubectl describe pod POD_NAME
kubectl describe node NODE_NAME
How to Check Node and Pod Resource Usage
Requires the metrics-server to be installed in the cluster.
kubectl top nodes
kubectl top pods
kubectl top pods -n NAMESPACE_NAME
How to Debug a CrashLoopBackOff Error
Start with logs from the previous container instance:
kubectl logs POD_NAME --previous
Then describe the pod to check exit codes and OOMKilled events:
kubectl describe pod POD_NAME
How to Check Why a Pod is Pending
A pod stays Pending when the scheduler can't place it. Run kubectl describe pod POD_NAME and check the Events section.
Common causes:
-
Insufficient CPU or memory on available nodes
-
No node matches the pod's
nodeSelectoror affinity rules -
PersistentVolumeClaim not bound
Kubernetes YAML Manifest Structure
How to Write a Pod Manifest
apiVersion: v1
kind: Pod
metadata:
name: my-pod
labels:
app: my-app
spec:
containers:
- name: my-container
image: nginx:1.25
ports:
- containerPort: 80
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
How to Write a Deployment Manifest
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-deployment
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-container
image: nginx:1.25
ports:
- containerPort: 80
How to Write a Service Manifest
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 80
type: ClusterIP
How to Apply and Delete Resources from a YAML File
Apply (create or update):
kubectl apply -f manifest.yaml
Delete resources defined in the file:
kubectl delete -f manifest.yaml
Apply all manifests in a directory:
kubectl apply -f ./manifests/
Essential kubectl Command Reference
Core commands with the most-used flags. Run any command with --help for the full flag list.
|
Command |
What it does |
|---|---|
|
|
List pods in current namespace |
|
|
List pods across all namespaces |
|
|
Node list with IPs and roles |
|
|
Full pod details and events |
|
|
Create or update from YAML |
|
|
Delete a pod |
|
|
Shell into a container |
|
|
Stream container logs |
|
|
Logs from crashed container |
|
|
Forward local port to pod |
|
|
Copy files from pod |
|
|
CPU and memory usage per pod |
|
|
Resource usage per node |
|
|
Mark node unschedulable |
|
|
Evict pods and cordon node |
|
|
Add taint to node |
|
|
Restart all pods in deployment |
|
|
Scale deployment |
|
|
Update container image |
|
|
Roll back to previous revision |
kubectl Output Formats
Control output with -o:
kubectl get pod POD_NAME -o yaml # Full YAML spec
kubectl get pod POD_NAME -o json # Full JSON spec
kubectl get pods -o wide # Extra columns (node, IP)
kubectl get pods -o name # Resource names only
JSONPath lets you extract specific fields:
kubectl get pod POD_NAME -o jsonpath='{.status.podIP}'
FAQ on Kubernetes Cheat Sheets
What is kubectl and why do I need it?
kubectl is the command-line tool for interacting with a Kubernetes cluster via the Kubernetes API.
Without it, you can't create pods, manage deployments, check logs, or run any cluster operations. It's the primary interface for every Kubernetes workflow.
What is the difference between a Pod and a Deployment?
A pod is a single instance of a running container. A Kubernetes deployment manages multiple pod replicas, handles rolling updates, and restarts failed pods automatically.
Use deployments in production. Bare pods don't self-heal.
How do I check why a pod is not running?
Start with kubectl describe pod POD_NAME and read the Events section at the bottom.
Then run kubectl logs POD_NAME --previous if the pod has crashed. Between these two commands, you'll find 90% of issues.
What is a kubeconfig file?
A kubeconfig file stores cluster credentials, context names, and namespace settings for kubectl.
It lives at ~/.kube/config by default. You can manage multiple clusters by adding contexts and switching between them with kubectl config use-context.
What is the difference between ClusterIP, NodePort, and LoadBalancer?
ClusterIP is internal only. NodePort exposes the service on a static port across all nodes. LoadBalancer provisions an external IP through your cloud provider (GKE, EKS, AKS).
Pick based on whether you need external traffic or not.
How do I store sensitive data in Kubernetes?
Use a Kubernetes Secret instead of hardcoding values in your YAML manifests.
Secrets can be mounted as environment variables or volumes. For production, back them with a secret manager like AWS Secrets Manager or HashiCorp Vault.
What does CrashLoopBackOff mean?
The container is starting, crashing, and restarting repeatedly. Kubernetes applies an increasing backoff delay between each restart attempt.
Run kubectl logs POD_NAME --previous to see what's failing. Common causes: bad config, missing environment variables, or an application error on startup.
How do I run a command inside a running container?
kubectl exec -it POD_NAME -- /bin/bash
If bash isn't available, try sh. For a quick one-off command without an interactive session, drop the -it flags and append the command directly.
What is a PersistentVolumeClaim in Kubernetes?
A PersistentVolumeClaim is how a pod requests storage from the cluster.
You define the size and access mode, and Kubernetes binds the claim to an available PersistentVolume. The pod then mounts it like a regular filesystem path.
How do I roll back a bad Kubernetes deployment?
kubectl rollout undo deployment/DEPLOY_NAME
This reverts to the previous revision. Use kubectl rollout history deployment/DEPLOY_NAME to see all revisions, then add --to-revision=N to roll back to a specific one.