Kubernetes Cheat Sheet
kubectl Context and Configuration
Manage which Kubernetes cluster kubectl communicates with, and configure authentication and namespace defaults.
kubectl config view # View merged kubeconfig
# Use multiple kubeconfig files simultaneously
export KUBECONFIG=~/.kube/config:~/.kube/kubconfig2
kubectl config view
# Extract a specific user's password
kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'
# List users
kubectl config view -o jsonpath='{.users[*].name}'
# Context management
kubectl config get-contexts # List contexts
kubectl config current-context # Show active context
kubectl config use-context my-cluster # Switch context
# Add a cluster entry
kubectl config set-cluster my-cluster
# Set proxy URL for cluster entry
kubectl config set-cluster my-cluster --proxy-url=my-proxy-url
# Add a user with basic authentication
kubectl config set-credentials kubeuser/foo.kubernetes.com \
--username=kubeuser --password=kubepassword
# Set default namespace for current context
kubectl config set-context --current --namespace=production
# Set a new context with specific namespace and user
kubectl config set-context gce --user=cluster-admin --namespace=foo \
&& kubectl config use-context gce
# Delete a user
kubectl config unset users.foo
Helpful aliases:
# Quickly switch or show context
alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ; } ; f'
# Quickly switch or show namespace
alias kn='f() { [ "$1" ] && kubectl config set-context --current --namespace $1 \
|| kubectl config view --minify | grep namespace | cut -d" " -f6 ; } ; f'
kubectl apply (Declarative Management)
kubectl apply is the recommended method for managing resources in production. It creates or updates resources by applying a desired state.
kubectl apply -f ./app.yaml # Apply single file
kubectl apply -f ./manifests/ # Apply directory
kubectl apply -f https://example.com/app.yaml # Apply from URL
kubectl create deployment nginx --image=nginx # Quick one-shot deployment
Create multiple manifests via stdin:
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: pod-one
spec:
containers:
- name: c
image: busybox
args: ["sleep", "1000"]
---
apiVersion: v1
kind: Pod
metadata:
name: pod-two
spec:
containers:
- name: c
image: busybox
args: ["sleep", "2000"]
EOF
Create a secret:
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
username: $(echo -n "jane" | base64 -w0)
password: $(echo -n "s33msi4" | base64 -w0)
EOF
Viewing and Finding Resources
kubectl get pods # Pods in namespace
kubectl get pods -A # All namespaces
kubectl get pods -o wide # Pod node placement
kubectl get deployments # Deployments
kubectl get svc # Services
kubectl describe pod my-pod # Detailed pod info
kubectl describe node my-node # Node details
Sorting:
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
kubectl get pv --sort-by=.spec.capacity.storage
Field and label selectors:
kubectl get pods --field-selector=status.phase=Running
kubectl get pods -l app=web
kubectl get nodes --selector='!node-role.kubernetes.io/control-plane'
Retrieve specific fields:
kubectl get configmap myconfig -o jsonpath='{.data.ca\.crt}'
kubectl get secret my-secret -o jsonpath='{.data.username}' | base64 --decode
Updating Resources and Rolling Updates
kubectl set image deployment/web web=nginx:1.25 # Update image
kubectl rollout history deployment/web # View history
kubectl rollout undo deployment/web # Roll back
kubectl rollout restart deployment/web # Rolling restart
kubectl rollout status deployment/web # Watch rollout
Patching Resources
kubectl patch node node1 -p '{"spec": {"unschedulable": true}}'
# Strategic merge patch
kubectl patch pod app-pod -p '{
"spec": {"containers":[{"name":"app","image":"new-image"}]}
}'
# JSON patch
kubectl patch pod app-pod --type=json -p='[
{"op":"replace","path":"/spec/containers/0/image","value":"new-image"}
]'
Editing Resources
kubectl edit svc/web-service
KUBE_EDITOR="nano" kubectl edit deployment/web
Change between:
ClusterIP
NodePort
LoadBalancer
ExternalName
Port
Targetport
NodePort
Protocol
Scaling Resources
kubectl scale deployment/web --replicas=5
kubectl scale -f deployment.yaml --replicas=4
Deleting Resources
kubectl delete -f ./app.yaml
kubectl delete pod my-pod --now
kubectl delete pods,svc -l app=web
kubectl delete pod,svc --all -n test
Interacting With Running Pods
kubectl logs my-pod
kubectl logs -f my-pod
kubectl exec my-pod -- ls /
kubectl exec -it my-pod -- sh
kubectl port-forward svc/web 8080:80
Copying Files to and from Containers
kubectl cp /tmp/localfile my-pod:/tmp/remote
kubectl cp my-pod:/tmp/remote /tmp/localfile
Advanced (using tar):
tar cf - . | kubectl exec -i my-pod -- tar xf - -C /tmp
Interacting With Nodes and Cluster
kubectl cordon node1
kubectl drain node1
kubectl uncordon node1
kubectl top node
kubectl top pod
kubectl cluster-info
kubectl cluster-info dump
Discovering API Resources
kubectl api-resources
kubectl api-resources --namespaced=true
kubectl api-resources -o wide
kubectl api-resources --verbs=list,get
Kubectl Output Formatting
kubectl get pods -o json
kubectl get pods -o yaml
kubectl get pods -o wide
kubectl get pods -o name
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
Custom columns:
kubectl get pods -A -o=custom-columns='IMAGE:spec.containers[*].image'
Kubectl Verbosity and Debugging
- –v=0 Minimal logs
- –v=2 Recommended default
- –v=4 Debug level
- –v=6+ Full HTTP request inspection
Production-Ready Deployment YAML (Corrected)
Below is a cleaned-up and production-ready Deployment YAML based on your original example.
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
namespace: my-namespace
labels:
app: nginx
spec:
replicas: 3
revisionHistoryLimit: 5
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 1000
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "300m"
memory: "256Mi"
readinessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 3
periodSeconds: 10
livenessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 10
periodSeconds: 20
securityContext:
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
Conclusion
Kubernetes Cheat Sheet
This Kubernetes cheat sheet is a comprehensive and practical reference for working with kubectl, managing kubeconfig files, deploying Kubernetes workloads, viewing and troubleshooting cluster resources, and interacting with running workloads. It also includes a corrected production-ready Deployment YAML example. Everything below is ready to copy and paste directly into your WordPress editor.
kubectl Context and Configuration
Manage which Kubernetes cluster kubectl communicates with, and configure authentication and namespace defaults.
kubectl config view # View merged kubeconfig
# Use multiple kubeconfig files simultaneously
export KUBECONFIG=~/.kube/config:~/.kube/kubconfig2
kubectl config view
# Extract a specific user's password
kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'
# List users
kubectl config view -o jsonpath='{.users[*].name}'
# Context management
kubectl config get-contexts # List contexts
kubectl config current-context # Show active context
kubectl config use-context my-cluster # Switch context
# Add a cluster entry
kubectl config set-cluster my-cluster
# Set proxy URL for cluster entry
kubectl config set-cluster my-cluster --proxy-url=my-proxy-url
# Add a user with basic authentication
kubectl config set-credentials kubeuser/foo.kubernetes.com \
--username=kubeuser --password=kubepassword
# Set default namespace for current context
kubectl config set-context --current --namespace=production
# Set a new context with specific namespace and user
kubectl config set-context gce --user=cluster-admin --namespace=foo \
&& kubectl config use-context gce
# Delete a user
kubectl config unset users.foo
Helpful aliases:
# Quickly switch or show context
alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ; } ; f'
# Quickly switch or show namespace
alias kn='f() { [ "$1" ] && kubectl config set-context --current --namespace $1 \
|| kubectl config view --minify | grep namespace | cut -d" " -f6 ; } ; f'
kubectl apply (Declarative Management)
kubectl apply is the recommended method for managing resources in production. It creates or updates resources by applying a desired state.
kubectl apply -f ./app.yaml # Apply single file
kubectl apply -f ./manifests/ # Apply directory
kubectl apply -f https://example.com/app.yaml # Apply from URL
kubectl create deployment nginx --image=nginx # Quick one-shot deployment
Create multiple manifests via stdin:
cat <
Create a secret:
cat <
Viewing and Finding Resources
kubectl get pods # Pods in namespace
kubectl get pods -A # All namespaces
kubectl get pods -o wide # Pod node placement
kubectl get deployments # Deployments
kubectl get svc # Services
kubectl describe pod my-pod # Detailed pod info
kubectl describe node my-node # Node details
Sorting:
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
kubectl get pv --sort-by=.spec.capacity.storage
Field and label selectors:
kubectl get pods --field-selector=status.phase=Running
kubectl get pods -l app=web
kubectl get nodes --selector='!node-role.kubernetes.io/control-plane'
Retrieve specific fields:
kubectl get configmap myconfig -o jsonpath='{.data.ca\.crt}'
kubectl get secret my-secret -o jsonpath='{.data.username}' | base64 --decode
Updating Resources and Rolling Updates
kubectl set image deployment/web web=nginx:1.25 # Update image
kubectl rollout history deployment/web # View history
kubectl rollout undo deployment/web # Roll back
kubectl rollout restart deployment/web # Rolling restart
kubectl rollout status deployment/web # Watch rollout
Patching Resources
kubectl patch node node1 -p '{"spec": {"unschedulable": true}}'
# Strategic merge patch
kubectl patch pod app-pod -p '{
"spec": {"containers":[{"name":"app","image":"new-image"}]}
}'
# JSON patch
kubectl patch pod app-pod --type=json -p='[
{"op":"replace","path":"/spec/containers/0/image","value":"new-image"}
]'
Editing Resources
kubectl edit svc/web-service
KUBE_EDITOR="nano" kubectl edit deployment/web
Scaling Resources
kubectl scale deployment/web --replicas=5
kubectl scale -f deployment.yaml --replicas=4
Deleting Resources
kubectl delete -f ./app.yaml
kubectl delete pod my-pod --now
kubectl delete pods,svc -l app=web
kubectl delete pod,svc --all -n test
Interacting With Running Pods
kubectl logs my-pod
kubectl logs -f my-pod
kubectl exec my-pod -- ls /
kubectl exec -it my-pod -- sh
kubectl port-forward svc/web 8080:80
Copying Files to and from Containers
kubectl cp /tmp/localfile my-pod:/tmp/remote
kubectl cp my-pod:/tmp/remote /tmp/localfile
Advanced (using tar):
tar cf - . | kubectl exec -i my-pod -- tar xf - -C /tmp
Interacting With Nodes and Cluster
kubectl cordon node1
kubectl drain node1
kubectl uncordon node1
kubectl top node
kubectl top pod
kubectl cluster-info
kubectl cluster-info dump
Discovering API Resources
kubectl api-resources
kubectl api-resources --namespaced=true
kubectl api-resources -o wide
kubectl api-resources --verbs=list,get
Kubectl Output Formatting
kubectl get pods -o json
kubectl get pods -o yaml
kubectl get pods -o wide
kubectl get pods -o name
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
Custom columns:
kubectl get pods -A -o=custom-columns='IMAGE:spec.containers[*].image'
Kubectl Verbosity and Debugging
- –v=0 Minimal logs
- –v=2 Recommended default
- –v=4 Debug level
- –v=6+ Full HTTP request inspection
Production-Ready Deployment YAML (Corrected)
Below is a cleaned-up and production-ready Deployment YAML based on your original example.
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
namespace: my-namespace
labels:
app: nginx
spec:
replicas: 3
revisionHistoryLimit: 5
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 1000
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "300m"
memory: "256Mi"
readinessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 3
periodSeconds: 10
livenessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 10
periodSeconds: 20
securityContext:
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
Conclusion
This Kubernetes cheat sheet provides a complete quick-reference for daily cluster operations, including context switching, applying manifests, rolling updates, patching, scaling, and debugging. With the included production-ready Deployment YAML and working examples, you can confidently operate Kubernetes clusters and deploy applications using the recommended declarative approach.
