kubectl Mastery — 40 Commands Every K8s Admin Needs
You can write perfect YAML manifests, but if you cannot navigate a cluster quickly with kubectl, you will drown during an incident. This post is your combat reference — 40 commands organized by category, each with real examples you can run right now. Bookmark this one.
Cluster Information (Commands 1-5)
Start every debugging session by understanding what cluster you are talking to.
# 1. Cluster info — API server endpoint and CoreDNS
kubectl cluster-info
# 2. Node list with resource usage
kubectl get nodes -o wide
# 3. Detailed node info (capacity, allocatable, conditions, taints)
kubectl describe node <node-name>
# 4. Component health status
kubectl get componentstatuses # deprecated in newer versions
kubectl get --raw='/readyz?verbose'
# 5. API versions available in this cluster
kubectl api-versions
kubectl api-resources | head -20
Resource Management — Get, Describe, Create (Commands 6-15)
Viewing Resources
# 6. List resources (pods, services, deployments, etc.)
kubectl get pods
kubectl get pods -A # All namespaces
kubectl get pods -n kube-system # Specific namespace
kubectl get pods -l app=nginx # By label selector
kubectl get pods --field-selector=status.phase=Running # By field
# 7. Get multiple resource types at once
kubectl get pods,svc,deployments
# 8. Detailed resource description (events, conditions, volumes)
kubectl describe pod <pod-name>
kubectl describe node <node-name>
kubectl describe svc <service-name>
# 9. Watch resources in real time
kubectl get pods -w
kubectl get events --sort-by='.lastTimestamp' -w
Creating and Modifying Resources
# 10. Apply a manifest (create or update)
kubectl apply -f deployment.yaml
kubectl apply -f ./manifests/ # Apply entire directory
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.7.0/aio/deploy/recommended.yaml
# 11. Create resources imperatively (quick testing)
kubectl run nginx --image=nginx:1.25 --port=80
kubectl create deployment api --image=myapi:1.0 --replicas=3
kubectl create service clusterip api --tcp=80:8080
kubectl create configmap app-config --from-literal=ENV=prod
kubectl create secret generic db-pass --from-literal=password=secret123
# 12. Edit a resource live (opens in $EDITOR)
kubectl edit deployment api-server
kubectl edit svc api-service
# 13. Delete resources
kubectl delete pod nginx
kubectl delete -f deployment.yaml
kubectl delete pods -l app=test # By label
kubectl delete pods --all -n staging # All pods in namespace
kubectl delete namespace staging # Everything in namespace
# 14. Dry run — validate without applying
kubectl apply -f deployment.yaml --dry-run=client
kubectl apply -f deployment.yaml --dry-run=server # Server-side validation
# 15. Generate YAML template (never write YAML from scratch)
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml
kubectl create deployment api --image=myapi:1.0 --replicas=3 --dry-run=client -o yaml > deploy.yaml
kubectl create service clusterip api --tcp=80:8080 --dry-run=client -o yaml > svc.yaml
Command 15 is a game-changer. Instead of writing YAML from memory, let kubectl generate it and edit what you need.
Debugging — Logs, Exec, Port-Forward (Commands 16-25)
This is where you spend most of your time during incidents.
# 16. View pod logs
kubectl logs <pod-name>
kubectl logs <pod-name> -c <container-name> # Specific container
kubectl logs <pod-name> --previous # Previous crashed container
kubectl logs <pod-name> -f # Follow (stream) logs
kubectl logs <pod-name> --tail=100 # Last 100 lines
kubectl logs <pod-name> --since=1h # Last hour
# 17. Logs from multiple pods at once
kubectl logs -l app=api --all-containers=true
kubectl logs deployment/api-server # All pods in deployment
# 18. Execute commands inside a container
kubectl exec <pod-name> -- ls /app
kubectl exec -it <pod-name> -- /bin/bash # Interactive shell
kubectl exec -it <pod-name> -c sidecar -- sh # Specific container
# 19. Port-forward to access a pod or service locally
kubectl port-forward pod/<pod-name> 8080:80
kubectl port-forward svc/api-service 8080:80
kubectl port-forward deployment/api-server 8080:80
# Now access: http://localhost:8080
# 20. Copy files to/from a pod
kubectl cp <pod-name>:/var/log/app.log ./app.log
kubectl cp ./config.yaml <pod-name>:/app/config.yaml
# 21. Resource usage (requires metrics-server)
kubectl top nodes
kubectl top pods
kubectl top pods --sort-by=memory
kubectl top pods -A --sort-by=cpu
# 22. Debug a running pod (ephemeral debug container)
kubectl debug -it <pod-name> --image=busybox --target=app
kubectl debug -it <pod-name> --image=nicolaka/netshoot --target=app
# 23. Debug a node
kubectl debug node/<node-name> -it --image=ubuntu
# 24. Get events (sorted by time)
kubectl get events --sort-by='.lastTimestamp'
kubectl get events --field-selector=reason=Failed
kubectl get events -n kube-system --sort-by='.lastTimestamp' | tail -20
# 25. Explain a resource field (built-in docs)
kubectl explain pod.spec.containers.livenessProbe
kubectl explain deployment.spec.strategy --recursive
Configuration and Context (Commands 26-30)
# 26. View kubeconfig
kubectl config view
kubectl config view --minify # Current context only
# 27. List and switch contexts
kubectl config get-contexts
kubectl config use-context production-cluster
kubectl config current-context
# 28. Set default namespace for context
kubectl config set-context --current --namespace=production
# 29. Merge multiple kubeconfigs
export KUBECONFIG=~/.kube/config:~/.kube/staging-config:~/.kube/prod-config
kubectl config get-contexts # Shows all contexts from all files
# 30. Create a new context
kubectl config set-context staging --cluster=staging-cluster --user=admin --namespace=staging
Advanced Operations (Commands 31-40)
Patching and Labeling
# 31. Patch a resource (strategic merge patch)
kubectl patch deployment api-server -p '{"spec":{"replicas":5}}'
kubectl patch svc api-service -p '{"spec":{"type":"LoadBalancer"}}'
# JSON patch for precise changes
kubectl patch deployment api-server --type='json' -p='[{"op":"replace","path":"/spec/replicas","value":5}]'
# 32. Label resources
kubectl label pods nginx env=production
kubectl label pods nginx env- # Remove a label
kubectl label pods -l app=api tier=backend # Label multiple at once
kubectl label nodes node-1 disktype=ssd # Label a node
# 33. Annotate resources
kubectl annotate deployment api-server kubernetes.io/change-cause="Upgraded to v2.0"
kubectl annotate deployment api-server description="Main API server"
Node Management
# 34. Taint a node (prevent scheduling)
kubectl taint nodes node-1 dedicated=gpu:NoSchedule
kubectl taint nodes node-1 dedicated=gpu:NoSchedule- # Remove taint
# 35. Cordon/Uncordon (mark node unschedulable)
kubectl cordon node-1 # No new pods will be scheduled
kubectl uncordon node-1 # Allow scheduling again
# 36. Drain a node (evacuate all pods for maintenance)
kubectl drain node-1 --ignore-daemonsets --delete-emptydir-data
kubectl drain node-1 --ignore-daemonsets --delete-emptydir-data --force
Scaling and Rollouts
# 37. Scale resources
kubectl scale deployment api-server --replicas=10
kubectl scale statefulset postgres --replicas=3
# 38. Rollout management
kubectl rollout status deployment/api-server
kubectl rollout history deployment/api-server
kubectl rollout undo deployment/api-server
kubectl rollout undo deployment/api-server --to-revision=3
kubectl rollout restart deployment/api-server
kubectl rollout pause deployment/api-server
kubectl rollout resume deployment/api-server
RBAC and Authorization
# 39. Check permissions
kubectl auth can-i create pods
kubectl auth can-i delete deployments --as=alice@company.com
kubectl auth can-i '*' '*' # Am I cluster admin?
kubectl auth can-i --list --as=alice@company.com -n production
Diff
# 40. Diff — see what would change before applying
kubectl diff -f deployment.yaml
This is underrated. Before applying any change in production, run kubectl diff first. It shows exactly what fields will change, like a git diff for your cluster.
Output Formatting
Master these output flags to extract exactly the data you need:
# Standard formats
kubectl get pods -o wide # Extra columns (IP, node)
kubectl get pods -o yaml # Full YAML
kubectl get pods -o json # Full JSON
kubectl get pods -o name # Just resource names
# Custom columns
kubectl get pods -o custom-columns='NAME:.metadata.name,STATUS:.status.phase,IP:.status.podIP,NODE:.spec.nodeName'
# JSONPath — surgical data extraction
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
kubectl get secret db-cred -o jsonpath='{.data.password}' | base64 -d
# Sort output
kubectl get pods --sort-by='.status.startTime'
kubectl get pods --sort-by='.spec.containers[0].resources.requests.memory'
kubectl get events --sort-by='.lastTimestamp'
kubectl Aliases and Shell Completion
Essential Aliases
# Add to ~/.bashrc or ~/.zshrc
alias k='kubectl'
alias kgp='kubectl get pods'
alias kgpa='kubectl get pods -A'
alias kgs='kubectl get svc'
alias kgd='kubectl get deployments'
alias kgn='kubectl get nodes'
alias kdp='kubectl describe pod'
alias kds='kubectl describe svc'
alias kl='kubectl logs'
alias klf='kubectl logs -f'
alias ke='kubectl exec -it'
alias kaf='kubectl apply -f'
alias kdf='kubectl delete -f'
alias kctx='kubectl config use-context'
alias kns='kubectl config set-context --current --namespace'
Shell Completion
# Bash
echo 'source <(kubectl completion bash)' >> ~/.bashrc
echo 'complete -o default -F __start_kubectl k' >> ~/.bashrc # Works with alias
# Zsh
echo 'source <(kubectl completion zsh)' >> ~/.zshrc
# Reload
source ~/.bashrc
kubeconfig Management
# Default location
cat ~/.kube/config
# Use a specific kubeconfig file
kubectl --kubeconfig=/path/to/config get pods
# Merge multiple kubeconfig files
KUBECONFIG=~/.kube/config:~/.kube/staging:~/.kube/production kubectl config view --merge --flatten > ~/.kube/merged-config
# Set as default
cp ~/.kube/merged-config ~/.kube/config
kubectl Plugins with krew
krew is the plugin manager for kubectl. It gives you access to 200+ community plugins.
# Install krew (https://krew.sigs.k8s.io/docs/user-guide/setup/install/)
kubectl krew install ctx # Fast context switching
kubectl krew install ns # Fast namespace switching
kubectl krew install neat # Clean up kubectl output (remove managed fields)
kubectl krew install tree # Show resource hierarchy
kubectl krew install images # Show container images in use
kubectl krew install resource-capacity # Show node resource usage
# Usage
kubectl ctx production-cluster
kubectl ns production
kubectl get pod nginx -o yaml | kubectl neat
kubectl tree deployment api-server
That wraps up the core Kubernetes series. You now have a solid foundation from pods to production operations. Next, we will explore advanced topics like Helm charts, Ingress controllers, and GitOps with ArgoCD.
