Kubernetes Cheat Sheet
Container orchestration. Pods, deployments, services, debugging.
Quick Reference
Section titled “Quick Reference”| Resource | Purpose | Key Commands |
|---|---|---|
| Pod | Smallest deployable unit, one or more containers | get, describe, logs |
| Deployment | Manages ReplicaSets, handles rollouts | apply, scale, rollout |
| Service | Stable network endpoint for pods | expose, port-forward |
| ConfigMap | Configuration data as key-value pairs | create configmap |
| Secret | Sensitive data (base64 encoded) | create secret |
| Namespace | Virtual cluster for resource isolation | -n, --all-namespaces |
Cluster Context
Section titled “Cluster Context”kubectl cluster-info # Display cluster infokubectl version # Client and server versionkubectl get nodes # List nodes in clusterkubectl get nodes -o wide # With IP addresses
# Context managementkubectl config current-context # Show current contextkubectl config get-contexts # List all contextskubectl config use-context <name> # Switch contextkubectl config set-context --current --namespace=<ns> # Set default namespaceViewing Resources
Section titled “Viewing Resources”# Basic listingkubectl get pods # Pods in current namespacekubectl get pods -n <namespace> # Pods in specific namespacekubectl get pods -A # Pods across all namespaceskubectl get pods -o wide # With node and IP infokubectl get pods -w # Watch for changes
# Multiple resource typeskubectl get all # Common resourceskubectl get pods,svc,deploy # Specific typeskubectl get all -A # Everything everywhere
# Output formatskubectl get pods -o yaml # YAML outputkubectl get pods -o json # JSON outputkubectl get pods -o name # Just names
# Describe for detailskubectl describe pod <name> # Detailed pod info with eventskubectl describe node <name> # Node detailskubectl describe deploy <name> # Deployment details# Run a podkubectl run nginx --image=nginx # Create pod imperativelykubectl run debug --image=busybox -it --rm -- sh # Temporary debug pod
# Logskubectl logs <pod> # View logskubectl logs <pod> -c <container> # Specific containerkubectl logs <pod> --previous # Previous container instancekubectl logs <pod> -f # Follow/stream logskubectl logs <pod> --tail=100 # Last 100 lineskubectl logs -l app=nginx # By label selector
# Execute commandskubectl exec <pod> -- ls /app # Run command in podkubectl exec -it <pod> -- /bin/sh # Interactive shellkubectl exec -it <pod> -c <container> -- sh # Specific container
# Copy fileskubectl cp <pod>:/path ./local # From pod to localkubectl cp ./local <pod>:/path # From local to pod
# Port forwardingkubectl port-forward <pod> 8080:80 # Forward local:podkubectl port-forward svc/<name> 8080:80 # Forward to serviceDeployments
Section titled “Deployments”# Createkubectl create deployment nginx --image=nginxkubectl create deployment nginx --image=nginx --replicas=3
# Apply from manifestkubectl apply -f deployment.yaml # Create or updatekubectl apply -f ./manifests/ # All files in directorykubectl apply -f https://url/manifest.yaml # From URL
# Scalekubectl scale deploy <name> --replicas=5kubectl autoscale deploy <name> --min=2 --max=10 --cpu-percent=80
# Update image (rolling update)kubectl set image deploy/<name> <container>=<image:tag>kubectl set image deploy/nginx nginx=nginx:1.25
# Rollout managementkubectl rollout status deploy/<name> # Watch rollout progresskubectl rollout history deploy/<name> # View historykubectl rollout undo deploy/<name> # Rollback to previouskubectl rollout undo deploy/<name> --to-revision=2 # Specific revisionkubectl rollout restart deploy/<name> # Restart all podskubectl rollout pause deploy/<name> # Pause rolloutkubectl rollout resume deploy/<name> # Resume rolloutServices
Section titled “Services”# Expose deploymentkubectl expose deploy <name> --port=80 --target-port=8080kubectl expose deploy <name> --type=NodePort --port=80kubectl expose deploy <name> --type=LoadBalancer --port=80
# Types# ClusterIP — internal only (default)# NodePort — exposed on each node's IP at static port# LoadBalancer — external load balancer (cloud/OrbStack)
# Get endpointskubectl get endpoints <service>kubectl get svc <name> -o wideConfigMaps & Secrets
Section titled “ConfigMaps & Secrets”# ConfigMapkubectl create configmap <name> --from-literal=key=valuekubectl create configmap <name> --from-file=config.propertieskubectl create configmap <name> --from-env-file=.envkubectl get configmap <name> -o yaml
# Secretskubectl create secret generic <name> --from-literal=password=secretkubectl create secret generic <name> --from-file=./credentialskubectl create secret docker-registry <name> \ --docker-server=<url> --docker-username=<user> --docker-password=<pass>
# View secret (base64 decoded)kubectl get secret <name> -o jsonpath='{.data.password}' | base64 -dNamespaces
Section titled “Namespaces”kubectl get namespaces # List namespaceskubectl create namespace <name> # Create namespacekubectl delete namespace <name> # Delete (and all resources in it)
# Set default namespacekubectl config set-context --current --namespace=<name>
# Shorthand for namespace flagkubectl get pods -n kube-systemkubectl get pods --all-namespaces # or -ALabels & Selectors
Section titled “Labels & Selectors”# Add/update labelskubectl label pod <name> env=prodkubectl label pod <name> env=staging --overwrite
# Remove labelkubectl label pod <name> env-
# Select by labelkubectl get pods -l app=nginxkubectl get pods -l 'env in (prod,staging)'kubectl get pods -l app=nginx,env=prodkubectl delete pods -l app=testDebugging
Section titled “Debugging”The Workflow: get → describe → logs
Section titled “The Workflow: get → describe → logs”# 1. Get overview — what's the status?kubectl get podskubectl get events --sort-by='.lastTimestamp'
# 2. Describe — what happened? (scheduling, mounts, probes)kubectl describe pod <name>
# 3. Logs — what's the app saying?kubectl logs <pod> --tail=50kubectl logs <pod> --previous # If container restartedCommon Pod States
Section titled “Common Pod States”| State | Meaning | Check |
|---|---|---|
| Pending | Not scheduled yet | describe for events |
| ContainerCreating | Pulling image or mounting volumes | describe for events |
| ImagePullBackOff | Can’t pull image | Image name, registry auth |
| CrashLoopBackOff | Container keeps crashing | logs --previous |
| Running | Container is running | May still be unhealthy |
| Terminating | Being deleted | Finalizers, stuck processes |
Debug Commands
Section titled “Debug Commands”# Check pod eventskubectl describe pod <name> | grep -A 20 Events
# Check resource usagekubectl top podskubectl top nodes
# Debug with ephemeral container (k8s 1.23+)kubectl debug -it <pod> --image=busybox --target=<container>
# Run debug pod in same namespacekubectl run debug --image=nicolaka/netshoot -it --rm -- /bin/bash
# Check DNS resolutionkubectl run test --image=busybox -it --rm -- nslookup kubernetes
# Check service connectivitykubectl run test --image=curlimages/curl -it --rm -- curl http://<service>:<port>Local Development with OrbStack
Section titled “Local Development with OrbStack”OrbStack provides a lightweight local Kubernetes cluster on macOS.
# Enable Kubernetes in OrbStack settings, or:orb start k8s # Start clusterorb stop k8s # Stop clusterorb restart k8s # Restart clusterorb delete k8s # Delete clusterOrbStack Advantages
Section titled “OrbStack Advantages”- 2-second startup — Fast cluster initialization
- Shared images — Built Docker images immediately available to pods
- Direct network access — All service types accessible from Mac
- Low resource usage — Battery-friendly, minimal CPU/disk
Network Access
Section titled “Network Access”# Services accessible directly from Mac:# - ClusterIP: Direct IP access# - NodePort: localhost:<port># - LoadBalancer: *.k8s.orb.local# - Pod IPs: Direct connection
# Example: Access a LoadBalancer servicekubectl apply -f deployment.yamlkubectl expose deploy nginx --type=LoadBalancer --port=80curl http://nginx.default.svc.cluster.local# Or: curl http://<service>.k8s.orb.localUsing Local Images
Section titled “Using Local Images”# Build image (no registry push needed)docker build -t myapp:latest .
# Use in pod (avoid :latest to prevent pull attempts)kubectl run myapp --image=myapp:v1
# Or use imagePullPolicy: Never in manifestManifests
Section titled “Manifests”Deployment Template
Section titled “Deployment Template”apiVersion: apps/v1kind: Deploymentmetadata: name: myapp labels: app: myappspec: replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp image: myapp:1.0 ports: - containerPort: 8080 env: - name: ENV_VAR value: "value" resources: requests: memory: "64Mi" cpu: "250m" limits: memory: "128Mi" cpu: "500m" livenessProbe: httpGet: path: /health port: 8080 initialDelaySeconds: 10 periodSeconds: 5 readinessProbe: httpGet: path: /ready port: 8080 initialDelaySeconds: 5 periodSeconds: 3Service Template
Section titled “Service Template”apiVersion: v1kind: Servicemetadata: name: myappspec: selector: app: myapp ports: - port: 80 targetPort: 8080 type: ClusterIP # or NodePort, LoadBalancerUseful Aliases
Section titled “Useful Aliases”# Add to ~/.bashrc or ~/.zshrcalias k='kubectl'alias kgp='kubectl get pods'alias kgs='kubectl get svc'alias kgd='kubectl get deploy'alias kga='kubectl get all'alias kd='kubectl describe'alias kl='kubectl logs'alias ke='kubectl exec -it'alias kaf='kubectl apply -f'alias kdf='kubectl delete -f'
# Shell completionsource <(kubectl completion bash) # or zshDeleting Resources
Section titled “Deleting Resources”kubectl delete pod <name> # Delete podkubectl delete deploy <name> # Delete deploymentkubectl delete svc <name> # Delete servicekubectl delete -f manifest.yaml # Delete from file
kubectl delete pods --all # All pods in namespacekubectl delete all --all # All common resourceskubectl delete all -l app=test # By label
# Force delete stuck podkubectl delete pod <name> --force --grace-period=0See Also
Section titled “See Also”- Docker — Container basics before orchestration
- Shell — Scripting for kubectl automation
- jq — Processing kubectl JSON output
- PostgreSQL
- System Design