Appearance
kubectl Cheatsheet
kubectl is the command-line tool for interacting with Kubernetes clusters. It allows you to deploy applications, inspect and manage cluster resources, and view logs.
Installation and Configuration
Installation
bash
# Linux installation
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
# macOS installation
brew install kubectl
# Windows installation (PowerShell)
curl.exe -LO "https://dl.k8s.io/release/v1.28.0/bin/windows/amd64/kubectl.exe"
# Verify installation
kubectl version --client
Configuration
bash
# View current configuration
kubectl config view
# Get current context
kubectl config current-context
# List all contexts
kubectl config get-contexts
# Switch context
kubectl config use-context my-cluster
# Set default namespace for current context
kubectl config set-context --current --namespace=my-namespace
# Create new context
kubectl config set-context my-context --cluster=my-cluster --user=my-user --namespace=my-namespace
# Delete context
kubectl config delete-context my-context
Cluster Access
bash
# Set cluster credentials
kubectl config set-cluster my-cluster --server=https://k8s-cluster.example.com --certificate-authority=ca.crt
# Set user credentials
kubectl config set-credentials my-user --client-certificate=client.crt --client-key=client.key
# Set credentials with token
kubectl config set-credentials my-user --token=bearer_token_here
# Merge kubeconfig files
KUBECONFIG=~/.kube/config:~/.kube/config2 kubectl config view --merge --flatten > ~/.kube/merged_config
Basic Commands
Get Resources
bash
# Get all resources
kubectl get all
kubectl get all --all-namespaces
# Get specific resources
kubectl get pods
kubectl get services
kubectl get deployments
kubectl get nodes
kubectl get namespaces
# Get with additional information
kubectl get pods -o wide
kubectl get pods --show-labels
kubectl get pods --sort-by=.metadata.creationTimestamp
# Get resources in specific namespace
kubectl get pods -n kube-system
kubectl get pods --all-namespaces
# Get resources with custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName
Describe Resources
bash
# Describe resources for detailed information
kubectl describe pod <pod-name>
kubectl describe service <service-name>
kubectl describe node <node-name>
kubectl describe deployment <deployment-name>
# Describe with namespace
kubectl describe pod <pod-name> -n <namespace>
Create and Apply
bash
# Create resources from file
kubectl create -f manifest.yaml
kubectl create -f https://raw.githubusercontent.com/example/manifest.yaml
# Apply resources (create or update)
kubectl apply -f manifest.yaml
kubectl apply -f directory/
kubectl apply -R -f directory/ # Recursive
# Create resources imperatively
kubectl create deployment nginx --image=nginx
kubectl create service clusterip nginx --tcp=80:80
kubectl create configmap app-config --from-literal=key=value
kubectl create secret generic app-secret --from-literal=password=secret
Delete Resources
bash
# Delete resources
kubectl delete pod <pod-name>
kubectl delete service <service-name>
kubectl delete deployment <deployment-name>
# Delete from file
kubectl delete -f manifest.yaml
# Delete all resources of a type
kubectl delete pods --all
kubectl delete deployments --all
# Delete with label selector
kubectl delete pods -l app=nginx
# Force delete (use with caution)
kubectl delete pod <pod-name> --force --grace-period=0
Pod Management
Pod Operations
bash
# List pods
kubectl get pods
kubectl get pods -o wide
kubectl get pods --field-selector=status.phase=Running
# Create pod from image
kubectl run nginx --image=nginx
kubectl run busybox --image=busybox --rm -it -- /bin/sh # Interactive pod
# Get pod logs
kubectl logs <pod-name>
kubectl logs <pod-name> -c <container-name> # Multi-container pod
kubectl logs -f <pod-name> # Follow logs
kubectl logs --previous <pod-name> # Previous container logs
kubectl logs -l app=nginx # Logs from all pods with label
# Execute commands in pod
kubectl exec <pod-name> -- ls /app
kubectl exec -it <pod-name> -- /bin/bash
kubectl exec -it <pod-name> -c <container-name> -- /bin/sh
# Port forwarding
kubectl port-forward <pod-name> 8080:80
kubectl port-forward service/<service-name> 8080:80
# Copy files to/from pod
kubectl cp <pod-name>:/path/to/file ./local-file
kubectl cp ./local-file <pod-name>:/path/to/file
kubectl cp <pod-name>:/path/to/file ./local-file -c <container-name>
Pod Debugging
bash
# Get pod events
kubectl get events --field-selector involvedObject.name=<pod-name>
# Debug pod startup issues
kubectl describe pod <pod-name>
kubectl logs <pod-name> --previous
# Check resource usage
kubectl top pod <pod-name>
kubectl top pod <pod-name> --containers
# Create debug pod
kubectl run debug --image=busybox --rm -it -- /bin/sh
kubectl run debug --image=nicolaka/netshoot --rm -it -- /bin/bash
Deployment Management
Deployment Operations
bash
# Create deployment
kubectl create deployment nginx --image=nginx:1.21
# Scale deployment
kubectl scale deployment nginx --replicas=3
kubectl scale deployment nginx --replicas=0 # Scale down to zero
# Update deployment image
kubectl set image deployment/nginx nginx=nginx:1.22
kubectl set image deployment/nginx nginx=nginx:1.22 --record
# Set environment variables
kubectl set env deployment/nginx ENV_VAR=production
# Edit deployment
kubectl edit deployment nginx
# Patch deployment
kubectl patch deployment nginx -p '{"spec":{"replicas":5}}'
Rollout Management
bash
# Check rollout status
kubectl rollout status deployment/nginx
# View rollout history
kubectl rollout history deployment/nginx
kubectl rollout history deployment/nginx --revision=2
# Rollback deployment
kubectl rollout undo deployment/nginx
kubectl rollout undo deployment/nginx --to-revision=2
# Restart deployment (rolling restart)
kubectl rollout restart deployment/nginx
# Pause/resume rollout
kubectl rollout pause deployment/nginx
kubectl rollout resume deployment/nginx
Service Management
Service Operations
bash
# Expose deployment as service
kubectl expose deployment nginx --port=80 --type=ClusterIP
kubectl expose deployment nginx --port=80 --type=NodePort
kubectl expose deployment nginx --port=80 --type=LoadBalancer
# Create service with specific target port
kubectl expose deployment nginx --port=80 --target-port=8080
# List services
kubectl get services
kubectl get svc
# Describe service
kubectl describe service nginx
# Get service endpoints
kubectl get endpoints nginx
# Test service connectivity
kubectl run test --image=busybox --rm -it -- wget -qO- http://nginx
ConfigMap and Secret Management
ConfigMap Operations
bash
# Create ConfigMap from literal values
kubectl create configmap app-config --from-literal=database_url=mysql://localhost:3306
kubectl create configmap app-config --from-literal=key1=value1 --from-literal=key2=value2
# Create ConfigMap from file
kubectl create configmap app-config --from-file=config.properties
kubectl create configmap app-config --from-file=key=config.properties
# Create ConfigMap from directory
kubectl create configmap app-config --from-file=config/
# View ConfigMap
kubectl get configmap app-config -o yaml
kubectl describe configmap app-config
# Edit ConfigMap
kubectl edit configmap app-config
Secret Operations
bash
# Create secret from literal values
kubectl create secret generic app-secret --from-literal=username=admin --from-literal=password=secret
# Create secret from file
kubectl create secret generic app-secret --from-file=username.txt --from-file=password.txt
# Create TLS secret
kubectl create secret tls tls-secret --cert=tls.crt --key=tls.key
# Create Docker registry secret
kubectl create secret docker-registry regcred --docker-server=registry.example.com --docker-username=user --docker-password=pass
# View secret (base64 encoded)
kubectl get secret app-secret -o yaml
# Decode secret value
kubectl get secret app-secret -o jsonpath='{.data.password}' | base64 --decode
# Edit secret
kubectl edit secret app-secret
Namespace Management
bash
# List namespaces
kubectl get namespaces
kubectl get ns
# Create namespace
kubectl create namespace my-namespace
# Delete namespace (deletes all resources in it)
kubectl delete namespace my-namespace
# Set default namespace for current context
kubectl config set-context --current --namespace=my-namespace
# Get resources in specific namespace
kubectl get pods -n my-namespace
# Get resources in all namespaces
kubectl get pods --all-namespaces
kubectl get pods -A # Short form
Resource Monitoring and Debugging
Resource Usage
bash
# Node resource usage
kubectl top nodes
kubectl top nodes --sort-by=cpu
kubectl top nodes --sort-by=memory
# Pod resource usage
kubectl top pods
kubectl top pods --sort-by=cpu
kubectl top pods --sort-by=memory
kubectl top pods --containers # Show container-level metrics
kubectl top pods -n kube-system
# Specific pod resource usage
kubectl top pod <pod-name>
kubectl top pod <pod-name> --containers
Events and Logs
bash
# Get cluster events
kubectl get events
kubectl get events --sort-by=.metadata.creationTimestamp
kubectl get events --field-selector type=Warning
# Get events for specific resource
kubectl get events --field-selector involvedObject.name=<pod-name>
# Watch events in real-time
kubectl get events --watch
# Cluster information
kubectl cluster-info
kubectl cluster-info dump
Troubleshooting
bash
# Check node status
kubectl get nodes
kubectl describe node <node-name>
# Check system pods
kubectl get pods -n kube-system
# Check API server health
kubectl get --raw='/healthz'
# Check component status (deprecated in newer versions)
kubectl get componentstatuses
kubectl get cs
# Network debugging
kubectl run netshoot --image=nicolaka/netshoot --rm -it -- /bin/bash
kubectl run busybox --image=busybox --rm -it -- /bin/sh
# DNS debugging
kubectl run debug --image=busybox --rm -it -- nslookup kubernetes.default
kubectl run debug --image=busybox --rm -it -- nslookup <service-name>.<namespace>.svc.cluster.local
Advanced Operations
Label and Annotation Management
bash
# Add labels
kubectl label pods <pod-name> environment=production
kubectl label nodes <node-name> disktype=ssd
# Remove labels
kubectl label pods <pod-name> environment-
# Update labels
kubectl label pods <pod-name> environment=staging --overwrite
# Add annotations
kubectl annotate pods <pod-name> description="Web server pod"
# Remove annotations
kubectl annotate pods <pod-name> description-
# Select resources by labels
kubectl get pods -l environment=production
kubectl get pods -l environment!=production
kubectl get pods -l 'environment in (production,staging)'
kubectl get pods -l 'environment notin (development)'
Field Selectors
bash
# Select by field values
kubectl get pods --field-selector status.phase=Running
kubectl get pods --field-selector spec.nodeName=node1
kubectl get events --field-selector type=Warning
kubectl get events --field-selector involvedObject.kind=Pod
# Combine multiple field selectors
kubectl get pods --field-selector status.phase=Running,spec.nodeName=node1
Output Formatting
bash
# JSON output
kubectl get pods -o json
kubectl get pod <pod-name> -o json
# YAML output
kubectl get pods -o yaml
kubectl get pod <pod-name> -o yaml
# Custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName
# JSONPath output
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
# Go template output
kubectl get pods -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
# Wide output (more columns)
kubectl get pods -o wide
Patch Operations
bash
# Strategic merge patch
kubectl patch deployment nginx -p '{"spec":{"replicas":3}}'
# JSON merge patch
kubectl patch deployment nginx --type='merge' -p='{"spec":{"replicas":3}}'
# JSON patch
kubectl patch deployment nginx --type='json' -p='[{"op": "replace", "path": "/spec/replicas", "value": 3}]'
# Patch from file
kubectl patch deployment nginx --patch-file=patch.yaml
Resource Quotas and Limits
bash
# Get resource quotas
kubectl get resourcequota
kubectl describe resourcequota
# Get limit ranges
kubectl get limitrange
kubectl describe limitrange
# Check resource usage against quotas
kubectl describe namespace <namespace-name>
Batch Operations
Jobs and CronJobs
bash
# Create job
kubectl create job pi --image=perl -- perl -Mbignum=bpi -wle 'print bpi(2000)'
# Create job from cronjob
kubectl create job --from=cronjob/backup-job backup-manual
# List jobs
kubectl get jobs
# Describe job
kubectl describe job pi
# Delete job
kubectl delete job pi
# List cronjobs
kubectl get cronjobs
kubectl get cj # Short form
# Suspend/resume cronjob
kubectl patch cronjob backup-job -p '{"spec":{"suspend":true}}'
kubectl patch cronjob backup-job -p '{"spec":{"suspend":false}}'
Bulk Operations
bash
# Delete all pods with label
kubectl delete pods -l app=nginx
# Delete all resources in namespace
kubectl delete all --all -n my-namespace
# Scale multiple deployments
kubectl scale deployment nginx web api --replicas=3
# Apply multiple files
kubectl apply -f deployment.yaml -f service.yaml -f ingress.yaml
# Apply all files in directory
kubectl apply -f ./manifests/
# Apply with recursive directory search
kubectl apply -R -f ./manifests/
Security and RBAC
Service Accounts
bash
# Create service account
kubectl create serviceaccount my-service-account
# List service accounts
kubectl get serviceaccounts
kubectl get sa # Short form
# Describe service account
kubectl describe serviceaccount my-service-account
# Get service account token
kubectl get secret $(kubectl get serviceaccount my-service-account -o jsonpath='{.secrets[0].name}') -o jsonpath='{.data.token}' | base64 --decode
RBAC Operations
bash
# Check permissions
kubectl auth can-i create pods
kubectl auth can-i create pods --as=system:serviceaccount:default:my-service-account
kubectl auth can-i '*' '*' # Check if cluster admin
# List roles and rolebindings
kubectl get roles
kubectl get rolebindings
kubectl get clusterroles
kubectl get clusterrolebindings
# Describe RBAC resources
kubectl describe role <role-name>
kubectl describe rolebinding <rolebinding-name>
# Create role
kubectl create role pod-reader --verb=get,list,watch --resource=pods
# Create rolebinding
kubectl create rolebinding read-pods --role=pod-reader --user=jane
# Create clusterrole
kubectl create clusterrole cluster-reader --verb=get,list,watch --resource=*
# Create clusterrolebinding
kubectl create clusterrolebinding cluster-read --clusterrole=cluster-reader --user=jane
Performance and Optimization
Resource Management
bash
# Check resource requests and limits
kubectl describe nodes | grep -A 5 "Allocated resources"
# Get resource usage
kubectl top nodes
kubectl top pods --all-namespaces
# Check pod resource specifications
kubectl get pods -o custom-columns=NAME:.metadata.name,CPU-REQUEST:.spec.containers[*].resources.requests.cpu,MEMORY-REQUEST:.spec.containers[*].resources.requests.memory
# Identify pods without resource limits
kubectl get pods -o json | jq '.items[] | select(.spec.containers[].resources.limits == null) | .metadata.name'
Cluster Analysis
bash
# Get cluster capacity
kubectl get nodes -o custom-columns=NAME:.metadata.name,CPU:.status.capacity.cpu,MEMORY:.status.capacity.memory
# Check node conditions
kubectl get nodes -o custom-columns=NAME:.metadata.name,STATUS:.status.conditions[-1].type
# Analyze pod distribution
kubectl get pods -o wide --all-namespaces | awk '{print $8}' | sort | uniq -c
# Check for failed pods
kubectl get pods --all-namespaces --field-selector=status.phase=Failed
Useful Aliases and Functions
bash
# Add to ~/.bashrc or ~/.zshrc
# Basic aliases
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kdel='kubectl delete'
alias kl='kubectl logs'
alias kex='kubectl exec -it'
# Advanced aliases
alias kgp='kubectl get pods'
alias kgs='kubectl get services'
alias kgd='kubectl get deployments'
alias kgn='kubectl get nodes'
# Functions
kns() {
kubectl config set-context --current --namespace=$1
}
kpf() {
kubectl port-forward $1 $2:$3
}
klf() {
kubectl logs -f $1
}
# Enable kubectl autocompletion
source <(kubectl completion bash) # For bash
source <(kubectl completion zsh) # For zsh
Common Patterns and Examples
Rolling Updates
bash
# Update deployment image
kubectl set image deployment/nginx nginx=nginx:1.22 --record
# Monitor rollout
kubectl rollout status deployment/nginx
# Rollback if needed
kubectl rollout undo deployment/nginx
Blue-Green Deployment
bash
# Create green deployment
kubectl create deployment nginx-green --image=nginx:1.22
# Scale green deployment
kubectl scale deployment nginx-green --replicas=3
# Update service selector to point to green
kubectl patch service nginx -p '{"spec":{"selector":{"app":"nginx-green"}}}'
# Remove blue deployment
kubectl delete deployment nginx-blue
Canary Deployment
bash
# Scale down main deployment
kubectl scale deployment nginx --replicas=8
# Create canary deployment
kubectl create deployment nginx-canary --image=nginx:1.22
kubectl scale deployment nginx-canary --replicas=2
# Both deployments serve traffic through same service
# Monitor metrics and gradually shift traffic
Debugging Network Issues
bash
# Create debug pod
kubectl run debug --image=nicolaka/netshoot --rm -it -- /bin/bash
# Inside debug pod:
# nslookup kubernetes.default
# nslookup <service-name>.<namespace>.svc.cluster.local
# curl http://<service-name>.<namespace>.svc.cluster.local
# traceroute <pod-ip>
Best Practices
Resource Specifications
bash
# Always specify resource requests and limits
kubectl run nginx --image=nginx --requests='cpu=100m,memory=128Mi' --limits='cpu=200m,memory=256Mi'
# Use appropriate restart policies
kubectl run job-pod --image=busybox --restart=OnFailure -- /bin/sh -c "echo hello"
kubectl run one-time-pod --image=busybox --restart=Never -- /bin/sh -c "echo hello"
Health Checks
bash
# Add health checks to deployments
kubectl patch deployment nginx -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","livenessProbe":{"httpGet":{"path":"/","port":80},"initialDelaySeconds":30,"periodSeconds":10}}]}}}}'
Security
bash
# Run containers as non-root
kubectl run secure-pod --image=nginx --dry-run=client -o yaml | kubectl patch -f - -p '{"spec":{"securityContext":{"runAsNonRoot":true,"runAsUser":1000}}}'
# Use read-only root filesystem
kubectl run secure-pod --image=nginx --dry-run=client -o yaml | kubectl patch -f - -p '{"spec":{"containers":[{"name":"secure-pod","securityContext":{"readOnlyRootFilesystem":true}}]}}'