Master Kubernetes with Essential kubectl Commands: From Cluster Overview to Advanced Ops
This comprehensive guide walks you through the most useful kubectl commands for Kubernetes, covering cluster inspection, pod lifecycle, services, networking, storage, troubleshooting, performance tuning, security, and automation, empowering ops engineers to manage containerized clusters efficiently.
Cluster Overview
# Show basic cluster information
kubectl cluster-info
# List all nodes with extended details
kubectl get nodes -o wide
# Describe a specific node (replace NODE_NAME)
kubectl describe node NODE_NAME
# Show resource usage for nodes and pods
kubectl top nodes
kubectl top pods --all-namespacesNamespace Management
# List all namespaces
kubectl get namespaces
# Create a new namespace (replace NAMESPACE)
kubectl create namespace NAMESPACE
# Delete a namespace (use with caution)
kubectl delete namespace NAMESPACE
# Set the default namespace for the current context
kubectl config set-context --current --namespace=NAMESPACEPod Lifecycle Management
Basic Pod Operations
# List all pods across all namespaces
kubectl get pods --all-namespaces
# List pods in a specific namespace (replace NAMESPACE)
kubectl get pods -n NAMESPACE
# Watch pod status changes in real time
kubectl get pods -w
# Show detailed information for a pod (replace POD_NAME and NAMESPACE)
kubectl describe pod POD_NAME -n NAMESPACE
# Delete a pod
kubectl delete pod POD_NAME -n NAMESPACE
# Force‑delete a stuck pod
kubectl delete pod POD_NAME --grace-period=0 --forceAdvanced Pod Queries
# Query pods by label selector (e.g., app=nginx)
kubectl get pods -l app=nginx
# Query pods by field selector (e.g., Running phase)
kubectl get pods --field-selector status.phase=Running
# Output a pod's full YAML definition (replace POD_NAME)
kubectl get pod POD_NAME -o yaml
# Show resource usage for a specific pod
kubectl top pod POD_NAME
# List pod names with their phases using JSONPath
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"
"}{end}'Service and Network Management
Service Operations
# List all services in all namespaces
kubectl get services --all-namespaces
# Describe a specific service (replace SERVICE_NAME)
kubectl describe service SERVICE_NAME
# Show service endpoints
kubectl get endpoints SERVICE_NAME
# Port‑forward to a pod for debugging (replace POD_NAME)
kubectl port-forward pod/POD_NAME 8080:80
# Port‑forward to a service for debugging (replace SERVICE_NAME)
kubectl port-forward service/SERVICE_NAME 8080:80
# Find pods selected by a service's selector (replace SERVICE_SELECTOR)
kubectl get pods -l SERVICE_SELECTORIngress Management
# List all Ingress resources
kubectl get ingress --all-namespaces
# Describe a specific Ingress (replace INGRESS_NAME)
kubectl describe ingress INGRESS_NAME
# View Ingress controller logs (example assumes nginx‑ingress)
kubectl logs -n ingress-nginx deployment/nginx-ingress-controllerNetwork Policies and Connectivity Testing
# List all NetworkPolicies
kubectl get networkpolicies --all-namespaces
# Test connectivity between pods (replace POD_NAME and TARGET_IP)
kubectl exec -it POD_NAME -- ping TARGET_IP
kubectl exec -it POD_NAME -- nslookup SERVICE_NAME
# View a pod's DNS configuration (replace POD_NAME)
kubectl exec -it POD_NAME -- cat /etc/resolv.confConfiguration and Storage Management
ConfigMap and Secret
# List all ConfigMaps
kubectl get configmaps --all-namespaces
# Show a ConfigMap's content (replace CONFIGMAP_NAME)
kubectl describe configmap CONFIGMAP_NAME
kubectl get configmap CONFIGMAP_NAME -o yaml
# Create a ConfigMap from a file or literal
kubectl create configmap NAME --from-file=FILE_PATH
kubectl create configmap NAME --from-literal=key=value
# List all Secrets
kubectl get secrets --all-namespaces
# Retrieve a Secret's data (Base64‑decoded) (replace SECRET_NAME)
kubectl get secret SECRET_NAME -o jsonpath='{.data.password}' | base64 -dPersistent Storage
# List PersistentVolumes
kubectl get pv
# List PersistentVolumeClaims
kubectl get pvc --all-namespaces
# Show StorageClasses
kubectl get storageclass
# Describe a PV or PVC (replace PV_NAME or PVC_NAME)
kubectl describe pv PV_NAME
kubectl describe pvc PVC_NAMETroubleshooting Techniques
Log Inspection
# View logs of a pod (replace POD_NAME and NAMESPACE)
kubectl logs POD_NAME -n NAMESPACE
# View logs of a specific container in a multi‑container pod (replace CONTAINER_NAME)
kubectl logs POD_NAME -c CONTAINER_NAME
# Follow logs in real time
kubectl logs -f POD_NAME
# Show logs of a previous (crashed) container
kubectl logs POD_NAME --previous
# Show logs from the last hour or from a specific timestamp
kubectl logs POD_NAME --since=1h
kubectl logs POD_NAME --since-time=2024-01-01T00:00:00Z
# Export logs of all pods to separate files (bash loop)
for pod in $(kubectl get pods -o name); do
kubectl logs $pod > ${pod##*/}.log 2>&1
doneEvent Analysis and Debugging
# List recent events sorted by timestamp
kubectl get events --sort-by='.lastTimestamp'
# Describe a specific resource to see its events (replace RESOURCE_TYPE and RESOURCE_NAME)
kubectl describe RESOURCE_TYPE RESOURCE_NAME
# Watch live changes of pods or events
kubectl get pods -w
kubectl get events -w
# Check node resource allocation details (replace NODE_NAME)
kubectl describe node NODE_NAME | grep -A5 "Allocated resources"Container Debugging
# Open a shell inside a container (replace POD_NAME)
kubectl exec -it POD_NAME -- /bin/bash
kubectl exec -it POD_NAME -- /bin/sh
# Execute a command in a specific container of a multi‑container pod (replace CONTAINER_NAME)
kubectl exec -it POD_NAME -c CONTAINER_NAME -- /bin/bash
# Copy files to/from a container (replace LOCAL_FILE, CONTAINER_PATH)
kubectl cp LOCAL_FILE POD_NAME:CONTAINER_PATH
kubectl cp POD_NAME:CONTAINER_PATH LOCAL_FILE
# Run a temporary debug pod
kubectl run debug-pod --rm -it --image=busybox -- /bin/sh
# Debug with a specialized image (e.g., netshoot)
kubectl debug POD_NAME -it --image=nicolaka/netshootPerformance Monitoring & Optimization
Resource Monitoring
# Show node resource usage
kubectl top nodes
# Show pod resource usage across the cluster
kubectl top pods --all-namespaces
# Show pod usage in a specific namespace (replace NAMESPACE)
kubectl top pods -n NAMESPACE
# Sort pods by CPU or memory usage
kubectl top pods --sort-by=cpu
kubectl top pods --sort-by=memoryScaling and Rollout Management
# Manually scale a Deployment (replace DEPLOYMENT_NAME)
kubectl scale deployment DEPLOYMENT_NAME --replicas=5
# View Horizontal Pod Autoscaler (HPA) status
kubectl get hpa
# View Vertical Pod Autoscaler (VPA) status
kubectl get vpa
# Check rollout status of a Deployment
kubectl rollout status deployment/DEPLOYMENT_NAME
# View rollout history
kubectl rollout history deployment/DEPLOYMENT_NAME
# Roll back to the previous version
kubectl rollout undo deployment/DEPLOYMENT_NAMEResource Quota Management
# List resource quotas
kubectl get resourcequota --all-namespaces
# List LimitRanges
kubectl get limitrange --all-namespaces
# Describe a specific quota (replace QUOTA_NAME)
kubectl describe resourcequota QUOTA_NAMEAdvanced Operations Tricks
Batch Actions & Automation
# Delete all Evicted pods
kubectl get pods --all-namespaces | grep Evicted | awk '{print $1, $2}' | xargs -n2 kubectl delete pod -n
# Restart all Deployments
kubectl get deployments -o name | xargs -I {} kubectl rollout restart {}
# Export image information of all pods
kubectl get pods --all-namespaces -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].image}{"
"}{end}'
# Find pods without resource limits (requires jq)
kubectl get pods --all-namespaces -o json | jq '.items[] | select(.spec.containers[].resources.limits == null) | .metadata.name'Security & Permission Management
# Show current user permissions
kubectl auth can-i --list
# Test a specific permission for a user (replace USERNAME)
kubectl auth can-i create pods --as=USERNAME
# List RBAC roles and bindings
kubectl get roles,rolebindings --all-namespaces
kubectl get clusterroles,clusterrolebindings
# List service accounts
kubectl get serviceaccounts --all-namespaces
# Show PodSecurityPolicies
kubectl get podsecuritypoliciesCluster Maintenance & Backup
# Drain a node for maintenance (replace NODE_NAME)
kubectl drain NODE_NAME --ignore-daemonsets --delete-emptydir-data
# Mark a node unschedulable
kubectl cordon NODE_NAME
# Make a node schedulable again
kubectl uncordon NODE_NAME
# Export all cluster resources to YAML (backup)
kubectl get all --all-namespaces -o yaml > cluster-backup.yaml
# Export ConfigMaps and Secrets separately
kubectl get configmaps --all-namespaces -o yaml > configmaps-backup.yaml
kubectl get secrets --all-namespaces -o yaml > secrets-backup.yamlCommand‑Line Ergonomics
# Create shortcuts for frequent commands
alias k='kubectl'
alias kgp='kubectl get pods'
alias kgs='kubectl get services'
alias kgn='kubectl get nodes'
alias kdp='kubectl describe pod'
alias kl='kubectl logs'
# Switch clusters quickly (requires kubectx)
kubectx CLUSTER_NAME
# Switch namespaces quickly (requires kubens)
kubens NAMESPACESigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
