kubectl Cheat Sheet for Daily Use
kubectl is the indispensable command-line tool for interacting with Kubernetes clusters. Mastering its various subcommands and flags is crucial for…
kubectl is the indispensable command-line tool for interacting with Kubernetes clusters. Mastering its various subcommands and flags is crucial for efficient cluster administration, application deployment, and troubleshooting. This reference aims to provide a practical cheat sheet covering the most frequently used kubectl operations, focusing on real-world scenarios for network engineers, sysadmins, and developers.
Initial Setup and Configuration
Before diving into commands, ensure your kubectl environment is correctly set up. This includes installing kubectl and configuring access to your Kubernetes cluster via a kubeconfig file. For convenience, aliasing kubectl to k and enabling shell auto-completion are highly recommended.
Install kubectl
Installation methods vary by OS. For Linux, using curl and apt (Debian/Ubuntu) or yum (RHEL/CentOS) is common:
# For Linux (e.g., Debian/Ubuntu)
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
# Verify installation
kubectl version --client
Configure kubeconfig
Your kubeconfig file (typically ~/.kube/config) contains cluster connection details, user authentication, and context information. Multiple clusters can be managed from a single file.
- View current context:
kubectl config current-context - List all contexts:
kubectl config get-contexts - Switch context:
kubectl config use-context <context-name>
Alias and Shell Completion
Saving keystrokes is paramount. For Bash, add these to your ~/.bashrc:
alias k=kubectl
complete -F __start_kubectl k
For Zsh, add to ~/.zshrc:
alias k=kubectl
source <(kubectl completion zsh) # For Zsh 5.2 and later
Remember to source ~/.bashrc or source ~/.zshrc after adding.
Resource Inspection and Discovery
Understanding the state of your cluster and its resources is fundamental. These commands help you list, describe, and inspect various Kubernetes objects.
Listing Resources
The get command is your primary tool for retrieving resource information.
- List all pods in all namespaces:
k get pods -A - List all pods with more details (IPs, node names):
k get pods -A -o wide - List deployments in a specific namespace:
k get deploy -n my-app-ns - List services and ingress:
k get svc,ing - List all resources in the current namespace:
k get all(useful for quick overview, but be specific for automation) - List custom resource definitions (CRDs):
k get crd - Filtering resources by label:
k get pods -l app=nginx,env=prod - Show resource usage (requires Metrics Server):
k top nodes,k top pods -n my-app-ns
Describing Resources
When get isn't enough, describe provides a wealth of detailed information, including events, container states, volumes, and network configurations.
- Detailed information about a pod:
k describe pod <pod-name> - Detailed information about a deployment:
k describe deploy <deployment-name> -n my-app-ns - Checking node status and capacity:
k describe node <node-name> - Inspecting events related to a resource: Look for the "Events" section at the bottom of a
describeoutput.
Viewing Resource Definitions (YAML/JSON)
To see the full YAML or JSON definition of a live resource:
# Output in YAML
k get pod <pod-name> -o yaml
# Output in JSON
k get svc <service-name> -o json
# Get a specific field using JSONPath
k get pod <pod-name> -o jsonpath='{.status.podIP}'
k get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.addresses[?(@.type=="InternalIP")].address}{"\n"}{end}'
Application Logging and Debugging
Troubleshooting applications running in Kubernetes heavily relies on access to logs and the ability to execute commands inside containers.
Viewing Logs
- Stream logs from a pod:
k logs -f <pod-name> - Stream logs from a specific container within a pod:
k logs -f <pod-name> -c <container-name> - View previous container logs (e.g., after a crash):
k logs <pod-name> --previous - Show logs from the last 5 minutes:
k logs <pod-name> --since=5m - Show logs with a specific number of lines:
k logs <pod-name> --tail=100
Executing Commands in Containers
The exec command allows you to run shell commands or access a shell directly inside a running container, essential for debugging.
- Execute a command (e.g.,
ls -la /app) in a pod:k exec <pod-name> -- ls -la /app - Get an interactive shell in a pod:
k exec -it <pod-name> -- sh(orbash,ashdepending on the image) - Interactive shell in a specific container:
k exec -it <pod-name> -c <container-name> -- bash
Note: Some minimal container images (e.g., Alpine-based) might not have bash or even sh. Try ash if sh fails.
Network Debugging and Connectivity
Verifying network paths and service accessibility is a common task for network engineers.
Port Forwarding
Directly access a service or pod's port from your local machine, bypassing external load balancers or ingress controllers. Useful for local development or testing.
- Port forward a service:
k port-forward svc/api 8080:80(Local port 8080 maps to service port 80) - Port forward a pod:
k port-forward <pod-name> 9000:8080(Local port 9000 maps to pod port 8080)
This command runs in the foreground. Use & to run in the background, or Ctrl+C to terminate.
Copying Files To/From Containers
Transfer files for configuration, logs, or debugging tools.
- Copy file from local to pod:
k cp ./local_config.yaml <pod-name>:/app/config.yaml - Copy file from pod to local:
k cp <pod-name>:/var/log/app.log ./app.log
Resource Management and Lifecycle
These commands cover deploying, updating, and deleting resources, as well as managing their lifecycle.
Applying and Deleting Resources
Use apply for declarative management and delete for removal.
- Apply (create/update) resources from a file:
k apply -f my-deployment.yaml - Apply multiple files from a directory:
k apply -f ./manifests/ - Delete resources defined in a file:
k delete -f my-deployment.yaml - Delete a specific deployment:
k delete deploy/my-app-web -n my-app-ns - Delete all pods with a specific label:
k delete pods -l app=test-app - Delete all resources in a namespace (use with extreme caution):
k delete all --all -n <namespace>
Updating and Rolling Back Deployments
Managing application versions and handling deployment issues are daily tasks.
- Restart a deployment:
k rollout restart deploy/api(creates new pods with updated timestamps) - Check rollout status:
k rollout status deploy/api - View rollout history:
k rollout history deploy/api - Rollback to a previous revision:
k rollout undo deploy/api - Rollback to a specific revision:
k rollout undo deploy/api --to-revision=2
Scaling Resources
Adjusting the number of replicas for deployments or replica sets.
- Scale a deployment to 5 replicas:
k scale deploy/my-app --replicas=5 - Scale a replica set:
k scale rs/my-app-xxxxxx --replicas=3
Common Pitfalls and Troubleshooting Tips
- Incorrect Context: Always verify your current cluster context (
k config current-context) before executing commands that modify resources. Accidentally modifying the wrong cluster is a common and costly error. - Namespace Mismatch: Many commands are namespace-scoped. If a resource isn't found, ensure you're in the correct namespace or use the
-n <namespace>flag. - Resource Not Found: Double-check the resource name and type. Use
k get allork api-resourcesto list available resource types. - Pod in Pending State: Usually indicates insufficient resources (CPU, Memory) or unavailable nodes. Use
k describe pod <pod-name>andk describe node <node-name>(if applicable) to check for scheduling events. - Pod in CrashLoopBackOff: The application inside the container is repeatedly crashing. Use
k logs <pod-name> --previousto see logs from the last crashed container. - ImagePullBackOff: Kubernetes cannot pull the container image. Check image name/tag, private registry credentials (ImagePullSecrets), and network connectivity.
- Service Not Accessible: Verify selectors match pod labels, check firewall rules (if external), and ensure endpoint objects exist and are populated (
k get ep <service-name>). - YAML Formatting Errors: YAML is whitespace sensitive. Use a linter or validator, or an IDE with YAML support. The
kubectl apply --dry-run=client -f <file> -o yamlcommand can help validate syntax before applying.