DEVOPS TRIBUNE ENGINEERING INTELLIGENCE FOR THE REAL WORLD
KUBERNETES CLI REFERENCE · 16 MIN READ
Kubernetes official logo

kubectl Master Guide: 55+ Commands Every DevOps Engineer Should Know

A production-tested kubectl master guide every DevOps engineer should know. Covers cluster contexts, node maintenance, pod debugging with ephemeral containers, Server-Side Apply, zero-downtime rollbacks, RBAC auditing, and JSONPath queries.

By DevOps Tribune Engineering Staff · Published November 28, 2026
kubectl Master Guide: 55+ Commands across Cluster, Nodes, Pods, Deploy, Rollout, Network, Debug, Config, Security, and Pro Tips

kubectl is the primary command-line interface for managing Kubernetes clusters. Whether you are deploying microservices in CI/CD pipelines, draining worker nodes for kernel patching, or triaging a production outage at 3:00 AM, fluent control over kubectl separates fast incident recovery from prolonged downtime.

This kubectl master guide organizes 55+ essential commands that every DevOps engineer should know into 11 operational domains. Every example uses production-safe flags verified against Kubernetes v1.28 through v1.35+.


1. What Is kubectl and How Does It Talk to the Kubernetes API?

kubectl is the official command-line client for Kubernetes. It reads cluster endpoints, TLS certificates, and user tokens from your local kubeconfig file (~/.kube/config) and translates terminal commands into authenticated HTTP REST requests sent directly to the control plane's kube-apiserver.

Understanding how kubectl interacts with the Kubernetes control plane and API server architecture prevents common operational mistakes. Every get, apply, or delete command maps to a standard HTTP verb (GET, POST, PATCH, DELETE) targeting a versioned API group such as apps/v1 or networking.k8s.io/v1. Kubernetes enforces a strict ±1 minor version skew policy between kubectl and kube-apiserver: a v1.35 client works reliably with v1.34, v1.35, and v1.36 clusters.

Verify kubectl Version & API Server Connectivity
# Check client and control-plane server versions
kubectl version

# Print control plane and CoreDNS service endpoints
kubectl cluster-info

# List all available API resource types, shortnames, and namespaced scope
kubectl api-resources

2. Cluster Context & Kubeconfig Commands

DevOps engineers routinely switch between staging, development, and multi-region production clusters. Running a destructive command against the wrong context is a classic human error, so inspecting and locking your active context before making changes is mandatory.

Manage Kubeconfig Contexts & Default Namespaces
# Display merged kubeconfig settings (redacts certificate data by default)
kubectl config view

# List all configured cluster contexts (* marks the active context)
kubectl config get-contexts

# Switch to a specific cluster context
kubectl config use-context prod-us-east-1

# Set a default namespace for the current context (avoids typing -n repeatedly)
kubectl config set-context --current --namespace=payments-prod

# Merge multiple kubeconfig files temporarily in your shell session
export KUBECONFIG=~/.kube/config:~/.kube/eks-staging.yaml

3. Node Operations: Inspect, Top, Cordon & Drain

Node-level commands reveal host capacity, kernel versions, taint configurations, and resource pressure. During OS upgrades or EC2 instance replacements, cordon and drain evacuate pods gracefully without dropping live client connections.

Inspect Node Health, Metrics, and Safe Eviction
# List all nodes with internal/external IPs, OS image, and container runtime
kubectl get nodes -o wide

# Inspect allocatable CPU/memory, conditions (DiskPressure/MemoryPressure), and running pods
kubectl describe node ip-10-0-14-82.ec2.internal

# Check real-time CPU and memory utilization per node (requires Metrics Server)
kubectl top nodes

# Mark a node unschedulable (existing pods remain running)
kubectl cordon ip-10-0-14-82.ec2.internal

# Safely evict pods while ignoring DaemonSets and clearing ephemeral emptyDir data
kubectl drain ip-10-0-14-82.ec2.internal --ignore-daemonsets --delete-emptydir-data

# Re-enable scheduling after node maintenance completes
kubectl uncordon ip-10-0-14-82.ec2.internal

Before draining production nodes, verify that critical workloads define a PodDisruptionBudget (PDB) as detailed in our Kubernetes production best practices guide. kubectl drain respects PDBs and pauses eviction rather than violating minimum replica availability.


4. Pod Lifecycle & Inspection Commands

Pods are the smallest deployable compute units in Kubernetes. Engineers use get, describe, top, and run dozens of times a day to verify placement, restart counts, and resource consumption.

Pod Discovery, Filtering & Ephemeral Testing
# List pods across all namespaces with node placement and Pod IP
kubectl get pods -A -o wide

# Filter pods by label selector and watch live state transitions
kubectl get pods -l app=checkout-api -w

# Sort pods by restart count to spot unstable workloads immediately
kubectl get pods -A --sort-by='.status.containerStatuses[0].restartCount'

# Inspect Pod events, container exit codes, probe failures, and volume mounts
kubectl describe pod checkout-api-7f9c8b-x2k9p

# Measure real-time CPU and RAM usage per container inside a Pod
kubectl top pods --containers --sort-by=memory

# Spin up a temporary interactive curl/dns test pod and auto-delete on exit
kubectl run net-test --rm -it --image=curlimages/curl --restart=Never -- sh

# Force-delete a pod stuck in Terminating state (use only after checking finalizers)
kubectl delete pod stuck-pod-0 --grace-period=0 --force

5. Deployments, Scaling & Server-Side Apply

While imperative commands work well for quick experiments, production environments rely on declarative YAML manifests. Traditional client-side kubectl apply stores the entire previous manifest in a kubectl.kubernetes.io/last-applied-configuration annotation, which hits size limits on large CRDs and causes field overwrites when multiple controllers manage the same resource.

Modern DevOps workflows use Server-Side Apply (--server-side) to track field-level ownership directly on the API server. Always validate manifest syntax with our online YAML & Kubernetes validator before applying changes to shared clusters, or pair manifests with automated GitOps controllers covered in our Argo CD vs Flux comparison.

Declarative Deployment, Diffing & Server-Side Apply
# Preview exact live cluster changes before applying a manifest
kubectl diff -f deployment.yaml

# Apply manifests using Server-Side Apply (eliminates last-applied annotation bloat)
kubectl apply --server-side -f deployment.yaml

# Resolve field ownership conflicts explicitly during Server-Side Apply
kubectl apply --server-side --force-conflicts -f deployment.yaml

# Scale a deployment imperatively during a traffic spike
kubectl scale deployment/checkout-api --replicas=8

# Configure Horizontal Pod Autoscaler (HPA) from CLI
kubectl autoscale deployment/checkout-api --min=3 --max=15 --cpu-percent=70

# Update a container image tag directly without editing local YAML
kubectl set image deployment/checkout-api api=ghcr.io/org/checkout:v2.4.1 --record=false

# Clean up all resources defined in a directory of manifests
kubectl delete -f ./k8s-manifests/

6. Rollouts, Restarts & Zero-Downtime Rollbacks

When a new release introduces elevated 5xx error rates or fails readiness probes, kubectl rollout gives you deterministic visibility into ReplicaSet revisions and one-command rollback recovery.

Monitor Rollouts, Trigger Restarts & Roll Back Revisions
# Block until the rolling update completes or fails (great for CI/CD gates)
kubectl rollout status deployment/checkout-api --timeout=180s

# View revision history (add --revision=N to inspect a specific template)
kubectl rollout history deployment/checkout-api

# Roll back immediately to the previous healthy ReplicaSet
kubectl rollout undo deployment/checkout-api

# Roll back to an exact historical revision number
kubectl rollout undo deployment/checkout-api --to-revision=4

# Trigger a graceful rolling restart (picks up updated ConfigMaps or Secrets)
kubectl rollout restart deployment/checkout-api

# Pause and resume a rollout mid-flight to inspect canary metrics
kubectl rollout pause deployment/checkout-api
kubectl rollout resume deployment/checkout-api

7. Networking, Services, Ingress & Port-Forward

Service discovery issues account for a large share of cluster incidents. Checking whether a Service actually populates Endpoints or EndpointSlices tells you immediately whether label selectors match healthy, ready Pods. For deeper packet-level diagnostics, see our container networking troubleshooting guide.

Inspect Services, Endpoints, Ingress & Local Port-Forwarding
# List Services with ClusterIP, External-IP, and Port mappings
kubectl get svc -A

# Verify that a Service selector resolves to healthy backend Pod IPs
kubectl get endpoints checkout-api

# Inspect Ingress hosts, TLS secrets, and path routing rules
kubectl get ingress -o wide

# Expose an existing Deployment as a ClusterIP Service
kubectl expose deployment/checkout-api --port=80 --target-port=8080

# Forward local port 8080 to a remote Pod or Service without exposing it publicly
kubectl port-forward svc/checkout-api 8080:80

# Forward to a specific Pod on all local interfaces (bind 0.0.0.0 carefully)
kubectl port-forward pod/prometheus-0 9090:9090

8. Debugging, Logs, Events & Ephemeral Containers

Production containers increasingly ship as minimal distroless or scratch images that contain zero shell binaries (sh/bash) or debugging utilities. Standard kubectl exec fails on these workloads, which makes kubectl debug ephemeral containers essential for modern SRE triage.

When triaging restarting containers, pair kubectl logs --previous with our CrashLoopBackOff troubleshooting runbook to distinguish Linux OOM kills (Exit Code 137) from missing binaries or failing liveness probes.

Stream Logs, Inspect Events & Attach Ephemeral Debug Containers
# Stream live logs for a specific container in a multi-container Pod
kubectl logs -f checkout-api-7f9c8b-x2k9p -c app --tail=100

# Retrieve logs from the crashed/previous container instance
kubectl logs checkout-api-7f9c8b-x2k9p --previous

# Aggregate logs across all Pods matching a label selector
kubectl logs -l app=checkout-api --all-containers=true --since=15m

# Sort cluster-wide events chronologically to correlate failures
kubectl get events -A --sort-by='.lastTimestamp'

# Execute an interactive shell inside a running container
kubectl exec -it checkout-api-7f9c8b-x2k9p -c app -- /bin/sh

# Copy diagnostic files or heap dumps out of a container to localhost
kubectl cp payments-prod/checkout-api-7f9c8b-x2k9p:/tmp/heap.hprof ./heap.hprof

# Attach an ephemeral busybox container sharing the target container's process namespace
kubectl debug -it checkout-api-7f9c8b-x2k9p --image=busybox:1.36 --target=app

# Debug a host worker node directly via a privileged host-namespace Pod
kubectl debug node/ip-10-0-14-82.ec2.internal -it --image=ubuntu:24.04

9. ConfigMaps, Secrets, Namespaces & Storage

Managing runtime configuration and persistent volumes from the CLI speeds up local staging setups and live verification. Remember that Kubernetes Secrets store values Base64-encoded by default—decode extracted secret fields safely using our offline Base64 Kubernetes Secret tool.

ConfigMaps, Secrets, Namespaces & Persistent Storage
# Create a ConfigMap from literal key-value pairs or an env file
kubectl create configmap app-config --from-literal=LOG_LEVEL=info --from-env-file=.env

# Create a generic Secret safely from local credential files
kubectl create secret generic db-creds --from-literal=password='S3curePass!'

# Extract and decode a single Secret key inline using jsonpath
kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 --decode

# List Namespaces, PersistentVolumeClaims (PVCs), PersistentVolumes, and StorageClasses
kubectl get ns
kubectl get pvc,pv -A
kubectl get storageclass

10. RBAC Security & Permission Auditing with kubectl auth

Least-privilege Role-Based Access Control (RBAC) protects clusters from compromised workloads. Before deploying a CI/CD runner or controller, audit exactly what actions a user or ServiceAccount can execute using kubectl auth can-i.

RBAC Inspection & Impersonation Checks
# List everything your current identity is permitted to do in the active namespace
kubectl auth can-i --list

# Check whether you can create deployments in a specific namespace
kubectl auth can-i create deployments -n payments-prod

# Impersonate a workload ServiceAccount to verify least-privilege boundaries
kubectl auth can-i get secrets -n kube-system --as=system:serviceaccount:payments-prod:checkout-sa

# Inspect ServiceAccounts, Roles, RoleBindings, and ClusterRoles
kubectl get sa,role,rolebinding -n payments-prod
kubectl get clusterroles,clusterrolebindings | grep -i admin

11. Pro Tips: JSONPath, Dry-Run YAML & Shell Productivity

Senior DevOps engineers rarely write Kubernetes YAML from scratch. Generating boilerplate manifests with --dry-run=client -o yaml and parsing cluster state with -o jsonpath saves hours every week—and is essential for timed CKA/CKAD exams.

Productivity Aliases, Dry-Run Generators & JSONPath Queries
# Enable bash/zsh autocomplete and short 'k' alias (add to ~/.zshrc or ~/.bashrc)
source <(kubectl completion zsh)
alias k=kubectl
complete -o default -F __start_kubectl k

# Generate clean Deployment YAML without creating anything on the cluster
kubectl create deployment web --image=nginx:1.27 --replicas=3 --dry-run=client -o yaml > deploy.yaml

# Inspect built-in schema documentation for any field directly in your terminal
kubectl explain pod.spec.containers.livenessProbe --recursive

# Extract all running container images across the cluster using JSONPath
kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}: {.spec.containers[*].image}{"\n"}{end}'

# Print custom columns showing Pod name, Node name, and CPU requests
kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,CPU_REQ:.spec.containers[0].resources.requests.cpu

Quick Reference Summary Table

Domain Essential Command Primary Use Case
Context kubectl config use-context <ctx> Switch active cluster safely
Nodes kubectl drain <node> --ignore-daemonsets Evict pods cleanly for host patching
Deploy kubectl apply --server-side -f app.yaml Field-level declarative reconciliation
Rollout kubectl rollout undo deploy/<name> Instant rollback to previous revision
Debug kubectl debug -it <pod> --image=busybox Inspect distroless containers live
Security kubectl auth can-i --as=... Audit ServiceAccount RBAC boundaries

12. kubectl Master Guide FAQ

What is kubectl and how does it work?

kubectl is the official command-line client for Kubernetes. It reads cluster endpoints and authentication tokens from your kubeconfig file (~/.kube/config) and sends HTTP REST requests to kube-apiserver to inspect, create, update, or delete cluster resources.

What is the difference between kubectl apply and kubectl create?

kubectl create is an imperative command that throws an AlreadyExists error if the object already exists. kubectl apply is declarative: it creates missing objects or patches existing ones to match your YAML manifest, and supports --server-side for conflict-aware field management.

How do I debug a CrashLoopBackOff pod with kubectl?

Run kubectl describe pod <name> to check exit codes and recent events, then inspect logs from the terminated container with kubectl logs <name> --previous. If the container uses a distroless image without a shell, attach an ephemeral container with kubectl debug -it <name> --image=busybox --target=<container>.

How do I switch Kubernetes namespaces permanently in kubectl?

Run kubectl config set-context --current --namespace=<namespace>. That updates your active kubeconfig context so every subsequent kubectl command targets that namespace automatically.

What is the difference between kubectl cordon and kubectl drain?

kubectl cordon marks a node as SchedulingDisabled so no new pods are scheduled onto it, leaving existing pods untouched. kubectl drain cordons the node and gracefully evicts running pods to other healthy nodes while honoring PodDisruptionBudgets.

How do I check RBAC permissions using kubectl auth can-i?

Run kubectl auth can-i <verb> <resource> to test your own access, or append --as=system:serviceaccount:<namespace>:<sa> to verify whether a specific workload ServiceAccount can read secrets or modify cluster state.

⚡ KUBERNETES & SRE INTERVIEW PREP

Preparing for Senior Kubernetes & Platform Interviews

Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.

Explore Kubernetes Interview Scenarios →