Kubectl Cheatsheet

A comprehensive reference guide for essential kubectl commands for daily Kubernetes operations.


Table of Contents


Cluster Information

# Get cluster information
kubectl cluster-info

# View cluster nodes
kubectl get nodes

# Show detailed node information
kubectl describe node <node-name>

# Check cluster version
kubectl version

# Get API resources available in cluster
kubectl api-resources

# Get API versions
kubectl api-versions

# Check cluster health
kubectl get componentstatuses
# or
kubectl get cs

Context and Configuration

# View current context
kubectl config current-context

# List all contexts
kubectl config get-contexts

# Switch context
kubectl config use-context <context-name>

# Set default namespace for current context
kubectl config set-context --current --namespace=<namespace>

# View kubeconfig
kubectl config view

# Set a custom kubeconfig file
kubectl --kubeconfig=/path/to/config get pods

# Create a new context
kubectl config set-context <context-name> \
  --cluster=<cluster-name> \
  --user=<user-name> \
  --namespace=<namespace>

# Delete a context
kubectl config delete-context <context-name>

# Rename context
kubectl config rename-context <old-name> <new-name>

Resource Management

Get Resources

# Get all resources in current namespace
kubectl get all

# Get all resources in all namespaces
kubectl get all --all-namespaces
# or
kubectl get all -A

# Get specific resource type
kubectl get pods
kubectl get deployments
kubectl get services
kubectl get nodes

# Get resources with wide output (more details)
kubectl get pods -o wide

# Get resources in specific namespace
kubectl get pods -n <namespace>

# Get resources with labels
kubectl get pods --show-labels

# Get resources sorted by creation time
kubectl get pods --sort-by=.metadata.creationTimestamp

# Get resources in JSON format
kubectl get pods -o json

# Get resources in YAML format
kubectl get pods -o yaml

# Get resources with custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase

# Watch resources in real-time
kubectl get pods --watch
# or
kubectl get pods -w

Describe Resources

# Describe a specific resource
kubectl describe pod <pod-name>
kubectl describe deployment <deployment-name>
kubectl describe service <service-name>

# Describe with namespace
kubectl describe pod <pod-name> -n <namespace>

# Describe all pods
kubectl describe pods

Create Resources

# Create resource from file
kubectl create -f <filename.yaml>

# Create resource from URL
kubectl create -f https://example.com/resource.yaml

# Create resource from directory
kubectl create -f ./configs/

# Apply configuration (create or update)
kubectl apply -f <filename.yaml>

# Create from stdin
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx:latest
EOF

# Create multiple resources
kubectl apply -f file1.yaml -f file2.yaml -f file3.yaml

Delete Resources

# Delete resource by name
kubectl delete pod <pod-name>
kubectl delete deployment <deployment-name>

# Delete using file
kubectl delete -f <filename.yaml>

# Delete all resources of a type
kubectl delete pods --all

# Delete with namespace
kubectl delete pod <pod-name> -n <namespace>

# Force delete a pod
kubectl delete pod <pod-name> --force --grace-period=0

# Delete resources by label
kubectl delete pods -l app=myapp

# Delete all resources in namespace
kubectl delete all --all -n <namespace>

Edit Resources

# Edit resource in default editor
kubectl edit pod <pod-name>
kubectl edit deployment <deployment-name>

# Edit with specific editor
KUBE_EDITOR="nano" kubectl edit pod <pod-name>

# Replace resource
kubectl replace -f <filename.yaml>

# Replace with force (delete and recreate)
kubectl replace --force -f <filename.yaml>

Pods

# List all pods
kubectl get pods

# List pods in all namespaces
kubectl get pods --all-namespaces

# Get pod details
kubectl describe pod <pod-name>

# Get pod logs
kubectl logs <pod-name>

# Get logs from specific container in pod
kubectl logs <pod-name> -c <container-name>

# Stream pod logs (follow)
kubectl logs -f <pod-name>

# Get previous pod logs (for crashed pods)
kubectl logs <pod-name> --previous

# Execute command in pod
kubectl exec <pod-name> -- <command>

# Get interactive shell in pod
kubectl exec -it <pod-name> -- /bin/bash
# or
kubectl exec -it <pod-name> -- /bin/sh

# Execute command in specific container
kubectl exec -it <pod-name> -c <container-name> -- /bin/bash

# Copy files to/from pod
kubectl cp <pod-name>:/path/to/file /local/path
kubectl cp /local/path <pod-name>:/path/to/file

# Port forward to pod
kubectl port-forward <pod-name> <local-port>:<pod-port>
# Example: kubectl port-forward nginx-pod 8080:80

# Get pod resource usage
kubectl top pod <pod-name>

# Get all pods resource usage
kubectl top pods

# Create a pod from command line
kubectl run nginx --image=nginx --restart=Never

# Create a pod with specific command
kubectl run busybox --image=busybox --restart=Never -- sleep 3600

# Create pod and expose it
kubectl run nginx --image=nginx --port=80 --expose

# Delete pod
kubectl delete pod <pod-name>

# Delete all pods
kubectl delete pods --all

# Get pod by label
kubectl get pods -l app=myapp

# Get pod status
kubectl get pods --field-selector=status.phase=Running

Deployments

# List deployments
kubectl get deployments

# Create deployment
kubectl create deployment <name> --image=<image>
# Example: kubectl create deployment nginx --image=nginx:1.21

# Create deployment with replicas
kubectl create deployment nginx --image=nginx:1.21 --replicas=3

# Get deployment details
kubectl describe deployment <deployment-name>

# Get deployment YAML
kubectl get deployment <deployment-name> -o yaml

# Edit deployment
kubectl edit deployment <deployment-name>

# Scale deployment
kubectl scale deployment <deployment-name> --replicas=5

# Autoscale deployment
kubectl autoscale deployment <deployment-name> --min=2 --max=10 --cpu-percent=80

# Update deployment image
kubectl set image deployment/<deployment-name> <container-name>=<new-image>
# Example: kubectl set image deployment/nginx nginx=nginx:1.22

# Check rollout status
kubectl rollout status deployment/<deployment-name>

# View rollout history
kubectl rollout history deployment/<deployment-name>

# Rollback to previous version
kubectl rollout undo deployment/<deployment-name>

# Rollback to specific revision
kubectl rollout undo deployment/<deployment-name> --to-revision=2

# Pause rollout
kubectl rollout pause deployment/<deployment-name>

# Resume rollout
kubectl rollout resume deployment/<deployment-name>

# Restart deployment (recreate all pods)
kubectl rollout restart deployment/<deployment-name>

# Delete deployment
kubectl delete deployment <deployment-name>

# Expose deployment as service
kubectl expose deployment <deployment-name> --port=80 --target-port=8080

# Get deployment replica sets
kubectl get rs -l app=<deployment-name>

Services

# List services
kubectl get services
# or
kubectl get svc

# Get service details
kubectl describe service <service-name>

# Create service
kubectl create service clusterip <service-name> --tcp=80:8080

# Expose deployment as service
kubectl expose deployment <deployment-name> --port=80 --target-port=8080

# Create NodePort service
kubectl expose deployment <deployment-name> --type=NodePort --port=80

# Create LoadBalancer service
kubectl expose deployment <deployment-name> --type=LoadBalancer --port=80

# Get service endpoints
kubectl get endpoints <service-name>

# Edit service
kubectl edit service <service-name>

# Delete service
kubectl delete service <service-name>

# Get service YAML
kubectl get service <service-name> -o yaml

# Port forward to service
kubectl port-forward service/<service-name> <local-port>:<service-port>

Namespaces

# List namespaces
kubectl get namespaces
# or
kubectl get ns

# Get current namespace
kubectl config view --minify --output 'jsonpath={..namespace}'

# Create namespace
kubectl create namespace <namespace-name>

# Create namespace from YAML
kubectl create -f - <<EOF
apiVersion: v1
kind: Namespace
metadata:
  name: <namespace-name>
EOF

# Delete namespace
kubectl delete namespace <namespace-name>

# Set default namespace for context
kubectl config set-context --current --namespace=<namespace-name>

# Get resources in specific namespace
kubectl get pods -n <namespace-name>

# Get resources in all namespaces
kubectl get pods --all-namespaces
# or
kubectl get pods -A

# Describe namespace
kubectl describe namespace <namespace-name>

# Get namespace resource quota
kubectl get resourcequota -n <namespace-name>

# Get namespace limit ranges
kubectl get limitrange -n <namespace-name>

ConfigMaps and Secrets

ConfigMaps

# Create ConfigMap from literal values
kubectl create configmap <config-name> --from-literal=key1=value1 --from-literal=key2=value2

# Create ConfigMap from file
kubectl create configmap <config-name> --from-file=<path/to/file>

# Create ConfigMap from directory
kubectl create configmap <config-name> --from-file=<path/to/directory>

# Create ConfigMap from env file
kubectl create configmap <config-name> --from-env-file=<path/to/env-file>

# List ConfigMaps
kubectl get configmaps
# or
kubectl get cm

# Describe ConfigMap
kubectl describe configmap <config-name>

# Get ConfigMap data
kubectl get configmap <config-name> -o yaml

# Edit ConfigMap
kubectl edit configmap <config-name>

# Delete ConfigMap
kubectl delete configmap <config-name>

Secrets

# Create secret from literal values
kubectl create secret generic <secret-name> --from-literal=username=admin --from-literal=password=secret

# Create secret from file
kubectl create secret generic <secret-name> --from-file=<path/to/file>

# Create TLS secret
kubectl create secret tls <secret-name> --cert=<path/to/cert> --key=<path/to/key>

# Create Docker registry secret
kubectl create secret docker-registry <secret-name> \
  --docker-server=<server> \
  --docker-username=<username> \
  --docker-password=<password> \
  --docker-email=<email>

# List secrets
kubectl get secrets

# Describe secret (data is hidden)
kubectl describe secret <secret-name>

# Get secret data (base64 encoded)
kubectl get secret <secret-name> -o yaml

# Decode secret data
kubectl get secret <secret-name> -o jsonpath='{.data.password}' | base64 --decode

# Edit secret
kubectl edit secret <secret-name>

# Delete secret
kubectl delete secret <secret-name>

Logs and Debugging

# View pod logs
kubectl logs <pod-name>

# Stream logs (follow)
kubectl logs -f <pod-name>

# View logs from specific container
kubectl logs <pod-name> -c <container-name>

# View previous container logs
kubectl logs <pod-name> --previous

# View logs from all containers in pod
kubectl logs <pod-name> --all-containers=true

# View logs with timestamps
kubectl logs <pod-name> --timestamps

# View last N lines of logs
kubectl logs <pod-name> --tail=100

# View logs since specific time
kubectl logs <pod-name> --since=1h
kubectl logs <pod-name> --since=2024-01-01T00:00:00Z

# View logs from multiple pods
kubectl logs -l app=myapp

# Get events
kubectl get events

# Get events sorted by time
kubectl get events --sort-by=.metadata.creationTimestamp

# Watch events
kubectl get events --watch

# Get events for specific resource
kubectl describe pod <pod-name> | grep Events: -A 10

# Check pod resource usage
kubectl top pod <pod-name>

# Check node resource usage
kubectl top node <node-name>

# Run debugging pod
kubectl run -it --rm debug --image=busybox --restart=Never -- sh

# Debug with specific image
kubectl run -it --rm debug --image=nicolaka/netshoot --restart=Never -- bash

# Attach to running container
kubectl attach <pod-name> -it

# Port forward for debugging
kubectl port-forward <pod-name> 8080:80

# Get pod details in JSON
kubectl get pod <pod-name> -o json

# Explain resource definition
kubectl explain pod
kubectl explain pod.spec.containers

# Dry run (test without creating)
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml

# Validate YAML without applying
kubectl apply -f deployment.yaml --dry-run=client

# Check API server connectivity
kubectl cluster-info dump

# Get API server logs
kubectl logs -n kube-system kube-apiserver-<node-name>

Scaling

# Scale deployment
kubectl scale deployment <deployment-name> --replicas=5

# Scale replica set
kubectl scale rs <replicaset-name> --replicas=3

# Scale statefulset
kubectl scale statefulset <statefulset-name> --replicas=3

# Auto scale based on CPU
kubectl autoscale deployment <deployment-name> --min=2 --max=10 --cpu-percent=80

# Get horizontal pod autoscaler
kubectl get hpa

# Describe autoscaler
kubectl describe hpa <hpa-name>

# Delete autoscaler
kubectl delete hpa <hpa-name>

# Scale to zero (stop all pods)
kubectl scale deployment <deployment-name> --replicas=0

# Edit autoscaler
kubectl edit hpa <hpa-name>

Rolling Updates and Rollbacks

# Update deployment image
kubectl set image deployment/<deployment-name> <container>=<new-image>:<tag>

# Update with record (saves in rollout history)
kubectl set image deployment/<deployment-name> <container>=<new-image> --record

# Check rollout status
kubectl rollout status deployment/<deployment-name>

# Watch rollout progress
kubectl rollout status deployment/<deployment-name> -w

# View rollout history
kubectl rollout history deployment/<deployment-name>

# View specific revision
kubectl rollout history deployment/<deployment-name> --revision=2

# Rollback to previous version
kubectl rollout undo deployment/<deployment-name>

# Rollback to specific revision
kubectl rollout undo deployment/<deployment-name> --to-revision=2

# Pause rollout
kubectl rollout pause deployment/<deployment-name>

# Resume paused rollout
kubectl rollout resume deployment/<deployment-name>

# Restart deployment (recreate pods)
kubectl rollout restart deployment/<deployment-name>

# Update resource limits
kubectl set resources deployment <deployment-name> -c=<container> --limits=cpu=200m,memory=512Mi

# Update environment variables
kubectl set env deployment/<deployment-name> ENV_VAR=value

# Remove environment variable
kubectl set env deployment/<deployment-name> ENV_VAR-

Resource Quotas and Limits

# Get resource quotas
kubectl get resourcequota
# or
kubectl get quota

# Describe resource quota
kubectl describe resourcequota <quota-name>

# Create resource quota from file
kubectl create -f quota.yaml

# Get limit ranges
kubectl get limitrange

# Describe limit range
kubectl describe limitrange <limitrange-name>

# View resource usage in namespace
kubectl top pods -n <namespace>
kubectl top nodes

# Get pod resource requests and limits
kubectl describe pod <pod-name> | grep -A 5 "Requests:"

Labels and Selectors

# Show labels for pods
kubectl get pods --show-labels

# Filter by label
kubectl get pods -l app=myapp
kubectl get pods -l env=production
kubectl get pods -l 'env in (production,staging)'

# Multiple label selectors
kubectl get pods -l app=myapp,env=production

# Label selector with inequality
kubectl get pods -l 'env!=production'

# Add label to resource
kubectl label pod <pod-name> env=production

# Update label
kubectl label pod <pod-name> env=staging --overwrite

# Remove label
kubectl label pod <pod-name> env-

# Label multiple resources
kubectl label pods --all env=production

# Label nodes
kubectl label node <node-name> disktype=ssd

# Get nodes by label
kubectl get nodes -l disktype=ssd

# Annotate resources
kubectl annotate pod <pod-name> description="My application pod"

# Remove annotation
kubectl annotate pod <pod-name> description-

# Show annotations
kubectl describe pod <pod-name> | grep Annotations:

Node Operations

# List nodes
kubectl get nodes

# Get node details
kubectl describe node <node-name>

# Get nodes with labels
kubectl get nodes --show-labels

# Label a node
kubectl label node <node-name> key=value

# Taint a node (prevent pods from scheduling)
kubectl taint nodes <node-name> key=value:NoSchedule

# Remove taint
kubectl taint nodes <node-name> key=value:NoSchedule-

# Cordon node (mark as unschedulable)
kubectl cordon <node-name>

# Uncordon node
kubectl uncordon <node-name>

# Drain node (evict pods before maintenance)
kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data

# Check node resource usage
kubectl top node <node-name>

# Get node conditions
kubectl get nodes -o json | jq '.items[].status.conditions'

# Get pods running on specific node
kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node-name>

Persistent Volumes

# List persistent volumes
kubectl get pv

# List persistent volume claims
kubectl get pvc

# Describe persistent volume
kubectl describe pv <pv-name>

# Describe persistent volume claim
kubectl describe pvc <pvc-name>

# Create PVC from file
kubectl create -f pvc.yaml

# Delete PVC
kubectl delete pvc <pvc-name>

# Get storage classes
kubectl get storageclass
# or
kubectl get sc

# Describe storage class
kubectl describe storageclass <sc-name>

# Set default storage class
kubectl patch storageclass <sc-name> -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'

# Get PV binding status
kubectl get pv -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,CLAIM:.spec.claimRef.name

Ingress

# List ingress resources
kubectl get ingress
# or
kubectl get ing

# Describe ingress
kubectl describe ingress <ingress-name>

# Get ingress YAML
kubectl get ingress <ingress-name> -o yaml

# Create ingress from file
kubectl create -f ingress.yaml

# Edit ingress
kubectl edit ingress <ingress-name>

# Delete ingress
kubectl delete ingress <ingress-name>

# Get ingress controllers
kubectl get pods -n ingress-nginx

# Get ingress class
kubectl get ingressclass

Jobs and CronJobs

# List jobs
kubectl get jobs

# Create job from image
kubectl create job <job-name> --image=<image>

# Create job with command
kubectl create job hello --image=busybox -- echo "Hello World"

# Get job details
kubectl describe job <job-name>

# Delete job
kubectl delete job <job-name>

# Delete job and its pods
kubectl delete job <job-name> --cascade=foreground

# List CronJobs
kubectl get cronjobs
# or
kubectl get cj

# Create CronJob
kubectl create cronjob <name> --image=<image> --schedule="*/5 * * * *" -- <command>

# Describe CronJob
kubectl describe cronjob <cronjob-name>

# Create job from CronJob manually
kubectl create job <job-name> --from=cronjob/<cronjob-name>

# Suspend CronJob
kubectl patch cronjob <cronjob-name> -p '{"spec":{"suspend":true}}'

# Resume CronJob
kubectl patch cronjob <cronjob-name> -p '{"spec":{"suspend":false}}'

# Delete CronJob
kubectl delete cronjob <cronjob-name>

# Get job logs
kubectl logs job/<job-name>

# Get pods created by job
kubectl get pods -l job-name=<job-name>

RBAC

# List roles
kubectl get roles

# List cluster roles
kubectl get clusterroles

# Describe role
kubectl describe role <role-name>

# List role bindings
kubectl get rolebindings

# List cluster role bindings
kubectl get clusterrolebindings

# Create role
kubectl create role <role-name> --verb=get,list --resource=pods

# Create cluster role
kubectl create clusterrole <role-name> --verb=get,list --resource=pods

# Create role binding
kubectl create rolebinding <binding-name> --role=<role-name> --user=<username>

# Create cluster role binding
kubectl create clusterrolebinding <binding-name> --clusterrole=<role-name> --user=<username>

# Check if user can perform action
kubectl auth can-i get pods
kubectl auth can-i create deployments

# Check permissions for another user
kubectl auth can-i get pods --as=<username>

# Create service account
kubectl create serviceaccount <sa-name>

# Get service accounts
kubectl get serviceaccounts
# or
kubectl get sa

# Bind service account to role
kubectl create rolebinding <binding-name> --role=<role-name> --serviceaccount=<namespace>:<sa-name>

# Get service account token
kubectl create token <sa-name>

# Describe service account
kubectl describe serviceaccount <sa-name>

Troubleshooting

Common Debugging Commands

# Check pod status and restarts
kubectl get pods -o wide

# Check why pod is not running
kubectl describe pod <pod-name> | grep -A 10 Events:

# Check pod logs
kubectl logs <pod-name> --previous

# Check node status
kubectl get nodes
kubectl describe node <node-name>

# Check cluster component status
kubectl get componentstatuses

# Check resource consumption
kubectl top nodes
kubectl top pods --all-namespaces

# Run diagnostic pod
kubectl run -it --rm debug --image=nicolaka/netshoot --restart=Never -- bash

# Test DNS resolution
kubectl run -it --rm debug --image=busybox --restart=Never -- nslookup kubernetes.default

# Test network connectivity
kubectl run -it --rm debug --image=busybox --restart=Never -- wget -O- http://service-name:port

# Get API server logs
kubectl logs -n kube-system <kube-apiserver-pod>

# Check etcd health
kubectl get --raw=/healthz/etcd

# Check scheduler logs
kubectl logs -n kube-system <kube-scheduler-pod>

# Check controller manager logs
kubectl logs -n kube-system <kube-controller-manager-pod>

Quick Fixes

# Restart a deployment
kubectl rollout restart deployment/<deployment-name>

# Delete and recreate a pod
kubectl delete pod <pod-name>

# Force delete stuck pod
kubectl delete pod <pod-name> --grace-period=0 --force

# Recreate all pods in deployment
kubectl scale deployment <deployment-name> --replicas=0
kubectl scale deployment <deployment-name> --replicas=3

# Clear failed pods
kubectl delete pods --field-selector=status.phase=Failed

# Clear evicted pods
kubectl get pods | grep Evicted | awk '{print $1}' | xargs kubectl delete pod

# Refresh all images in deployment
kubectl rollout restart deployment/<deployment-name>

# Uncordon all nodes
kubectl get nodes -o name | xargs -I {} kubectl uncordon {}

Useful Aliases

Add these to your .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'

# Namespace aliases
alias kgp='kubectl get pods'
alias kgpa='kubectl get pods --all-namespaces'
alias kgs='kubectl get services'
alias kgd='kubectl get deployments'
alias kgn='kubectl get nodes'

# Advanced aliases
alias kgpw='kubectl get pods --watch'
alias kgpwide='kubectl get pods -o wide'
alias kgpoyaml='kubectl get pods -o yaml'
alias kdp='kubectl describe pod'
alias kdd='kubectl describe deployment'
alias kds='kubectl describe service'

# Context aliases
alias kcc='kubectl config current-context'
alias kgc='kubectl config get-contexts'
alias kuc='kubectl config use-context'

# Apply/Delete aliases
alias ka='kubectl apply -f'
alias kaf='kubectl apply -f'
alias kdelf='kubectl delete -f'

# Logs aliases
alias klf='kubectl logs -f'
alias klp='kubectl logs -p'

# Port forwarding alias
alias kpf='kubectl port-forward'

Pro Tips

Use kubectl with JSON output and jq

# Get pod IPs
kubectl get pods -o json | jq '.items[].status.podIP'

# Get container images
kubectl get pods -o json | jq '.items[].spec.containers[].image'

# Get node capacity
kubectl get nodes -o json | jq '.items[].status.capacity'

# Get pod restart counts
kubectl get pods -o json | jq '.items[] | {name: .metadata.name, restarts: .status.containerStatuses[].restartCount}'

Use kubectl with custom columns

# Custom columns for pods
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName,IP:.status.podIP

# Custom columns for nodes
kubectl get nodes -o custom-columns=NAME:.metadata.name,STATUS:.status.conditions[-1].type,ROLE:.metadata.labels."node-role\.kubernetes\.io/control-plane"

Watch multiple resources

# Watch all resources
watch kubectl get all

# Watch pods and services
watch 'kubectl get pods,svc'

# Watch specific namespace
watch kubectl get pods -n production

Use dry-run for YAML generation

# Generate pod YAML
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml

# Generate deployment YAML
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > deployment.yaml

# Generate service YAML
kubectl create service clusterip myservice --tcp=80:80 --dry-run=client -o yaml > service.yaml

# Generate secret YAML
kubectl create secret generic mysecret --from-literal=password=secret --dry-run=client -o yaml > secret.yaml

Quick Reference Card






Additional Resources