Master Kubernetes with Essential Commands: Efficient Container Cluster Management
This comprehensive guide walks operations engineers through essential Kubernetes commands, covering cluster inspection, pod lifecycle, service and network handling, storage configuration, troubleshooting, performance monitoring, scaling, security, and automation, enabling efficient and expert management of containerized clusters.
Preface: As an operations engineer, mastering Kubernetes command-line tools is essential. This article thoroughly analyzes the most useful K8S commands, from basic operations to advanced techniques, helping you become an expert in managing containerized clusters.
Quick Navigation
Basic cluster information
Pod lifecycle management
Service and network management
Storage and configuration management
Fault diagnosis techniques
Advanced operations techniques
Practical tips
Basic Cluster Information
Cluster Status Overview
# View cluster info
kubectl cluster-info
# View node status
kubectl get nodes -o wide
# View node details
kubectl describe node <node-name>
# View cluster resource usage
kubectl top nodes
kubectl top pods --all-namespacesNamespace Management
# List all namespaces
kubectl get namespaces
# Create a namespace
kubectl create namespace <namespace-name>
# Delete a namespace (use with caution)
kubectl delete namespace <namespace-name>
# Set default namespace
kubectl config set-context --current --namespace=<namespace-name>Tip: Use kubectl config view --minify | grep namespace to quickly view the current namespace.
Pod Lifecycle Management
Basic Pod Operations
# List all Pods
kubectl get pods --all-namespaces
# List Pods in a specific namespace
kubectl get pods -n <namespace>
# Watch Pod status changes
kubectl get pods -w
# Describe a Pod
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 by label selector
kubectl get pods -l app=nginx
# Query by field selector
kubectl get pods --field-selector status.phase=Running
# View Pod YAML configuration
kubectl get pod <pod-name> -o yaml
# View Pod resource usage
kubectl top pod <pod-name>
# List all containers status
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"
"}{end}'Pro tip: Use kubectl get pods --sort-by=.metadata.creationTimestamp to sort by creation time and quickly locate newly deployed applications.
Service and Network Management
Service Management
# List all services
kubectl get services --all-namespaces
# Describe a service
kubectl describe service <service-name>
# View service endpoints
kubectl get endpoints <service-name>
# Temporary port forwarding (debugging)
kubectl port-forward pod/<pod-name> 8080:80
kubectl port-forward service/<service-name> 8080:80
# List Pods matching a service selector
kubectl get pods -l <service-selector>Ingress Management
# List Ingress rules
kubectl get ingress --all-namespaces
# Describe Ingress
kubectl describe ingress <ingress-name>
# View Ingress controller logs
kubectl logs -n ingress-nginx deployment/nginx-ingress-controllerNetwork Policies and Troubleshooting
# List network policies
kubectl get networkpolicies --all-namespaces
# Test Pod-to-Pod connectivity
kubectl exec -it <pod-name> -- ping <target-ip>
kubectl exec -it <pod-name> -- nslookup <service-name>
# View DNS configuration
kubectl exec -it <pod-name> -- cat /etc/resolv.confStorage and Configuration Management
ConfigMap and Secret
# List ConfigMaps
kubectl get configmaps --all-namespaces
# Describe ConfigMap
kubectl describe configmap <configmap-name>
kubectl get configmap <configmap-name> -o yaml
# Create ConfigMap
kubectl create configmap <name> --from-file=<file-path>
kubectl create configmap <name> --from-literal=key=value
# List Secrets
kubectl get secrets --all-namespaces
# View Secret (Base64 decoded)
kubectl get secret <secret-name> -o jsonpath='{.data.password}' | base64 -dPersistent Storage
# List PersistentVolumes
kubectl get pv
# List PersistentVolumeClaims
kubectl get pvc --all-namespaces
# List StorageClasses
kubectl get storageclass
# Describe PV and PVC
kubectl describe pv <pv-name>
kubectl describe pvc <pvc-name>Performance tip: Use
kubectl get pvc -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,VOLUME:.spec.volumeName,CAPACITY:.status.capacity.storage,STORAGECLASS:.spec.storageClassNameto quickly view storage overview.
Fault Diagnosis Techniques
Log Viewing and Analysis
# View Pod logs
kubectl logs <pod-name> -n <namespace>
# View specific container logs in multi-container Pod
kubectl logs <pod-name> -c <container-name>
# Follow logs in real time
kubectl logs -f <pod-name>
# View previous container logs after crash
kubectl logs <pod-name> --previous
# View logs since a specific time
kubectl logs <pod-name> --since=1h
kubectl logs <pod-name> --since-time=2024-01-01T00:00:00Z
# Export all Pod logs
for pod in $(kubectl get pods -o name); do
kubectl logs $pod > ${pod##*/}.log 2>&1
doneContainer Debugging
# Enter container shell
kubectl exec -it <pod-name> -- /bin/bash
kubectl exec -it <pod-name> -- /bin/sh
# Specify container in multi-container Pod
kubectl exec -it <pod-name> -c <container-name> -- /bin/bash
# Copy files to/from container
kubectl cp <local-file> <pod-name>:<container-path>
kubectl cp <pod-name>:<container-path> <local-file>
# Run temporary debug container
kubectl run debug-pod --rm -it --image=busybox -- /bin/sh
# Debug in existing network namespace
kubectl debug <pod-name> -it --image=nicolaka/netshootEvent and Status Analysis
# View cluster events
kubectl get events --sort-by='.lastTimestamp'
# Describe specific resource events
kubectl describe <resource-type> <resource-name>
# Watch resource changes
kubectl get pods -w
kubectl get events -w
# View node resource allocation
kubectl describe node <node-name> | grep -A 5 "Allocated resources"Fault isolation steps:
Check Pod status: kubectl get pods Inspect events: kubectl describe pod <pod-name> View logs: kubectl logs <pod-name> Enter container for debugging:
kubectl exec -it <pod-name> -- /bin/bashPerformance Monitoring and Optimization
Resource Monitoring
# View node resource usage
kubectl top nodes
# View Pod resource usage
kubectl top pods --all-namespaces
# View namespace-specific usage
kubectl top pods -n <namespace>
# Sort by CPU usage
kubectl top pods --sort-by=cpu
# Sort by memory usage
kubectl top pods --sort-by=memoryScaling Management
# Manually scale a Deployment
kubectl scale deployment <deployment-name> --replicas=5
# View Horizontal Pod Autoscaler
kubectl get hpa
# View Vertical Pod Autoscaler
kubectl get vpa
# Check Deployment rollout status
kubectl rollout status deployment/<deployment-name>
# View rollout history
kubectl rollout history deployment/<deployment-name>
# Roll back to previous version
kubectl rollout undo deployment/<deployment-name>Resource Quota Management
# List resource quotas
kubectl get resourcequota --all-namespaces
# List LimitRanges
kubectl get limitrange --all-namespaces
# Describe a specific quota
kubectl describe resourcequota <quota-name>Advanced Operations Techniques
Batch Operations and Automation
# Delete Evicted Pods in bulk
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 {}
# List images of all Pods
kubectl get pods --all-namespaces -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].image}{"
"}{end}'
# Find Pods without resource limits
kubectl get pods --all-namespaces -o json | jq '.items[] | select(.spec.containers[].resources.limits == null) | .metadata.name'Security and Permission Management
# View current user permissions
kubectl auth can-i --list
# Check specific user permission
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
# View PodSecurityPolicies
kubectl get podsecuritypoliciesCluster Maintenance and Backup
# Drain node for maintenance
kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data
# Cordon node (unschedulable)
kubectl cordon <node-name>
# Uncordon node
kubectl uncordon <node-name>
# Export all resources for backup
kubectl get all --all-namespaces -o yaml > cluster-backup.yaml
# Export ConfigMaps and Secrets
kubectl get configmaps --all-namespaces -o yaml > configmaps-backup.yaml
kubectl get secrets --all-namespaces -o yaml > secrets-backup.yamlPerformance Tuning Commands
# View component statuses
kubectl get componentstatuses
# Get API server metrics
kubectl get --raw /metrics
# View scheduler queue
kubectl get events --field-selector reason=FailedScheduling
# Analyze Pod start times
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,START_TIME:.status.startTime,NODE:.spec.nodeNamePractical Tips
Command Line Optimization
# Set aliases for efficiency
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'
# Use kubectx to switch clusters quickly
kubectx <cluster-name>
# Use kubens to switch namespaces quickly
kubens <namespace-name>Output Formatting
# JSON output
kubectl get pods -o json
# YAML output
kubectl get pods -o yaml
# Custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName
# JSONPath extraction
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# Formatted output with jq
kubectl get pods -o json | jq '.items[] | {name: .metadata.name, status: .status.phase}'Summary and Best Practices
Daily Operations Checklist
Cluster health check
Node status: kubectl get nodes System Pods: kubectl get pods -n kube-system Resource usage: kubectl top nodes Application status monitoring
Pod status: kubectl get pods --all-namespaces Service status: kubectl get services --all-namespaces Event monitoring: kubectl get events --sort-by='.lastTimestamp' Performance optimization checks
Resource quotas: kubectl describe node <node-name> HPA status: kubectl get hpa Storage usage:
kubectl get pvc --all-namespacesSecurity Operations Guidelines
Regularly back up ConfigMaps, Secrets, and PersistentVolumes.
Set appropriate resource limits and quotas.
Monitor abnormal events and failed scheduling.
Keep cluster component versions up to date.
Final Note
Mastering these Kubernetes commands equips you with core skills for efficient container cluster management. Practice in a test environment, and you’ll be able to quickly locate and resolve issues when they arise.
Signed-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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
