Cloud Native 15 min read

Essential kubectl Commands for Efficient Kubernetes Management

This guide compiles a comprehensive set of kubectl and Docker commands for retrieving logs, sorting pods, managing secrets, cleaning resources, debugging, port forwarding, and performing cluster maintenance tasks, helping administrators streamline Kubernetes operations and troubleshoot issues effectively.

Ops Development Stories
Ops Development Stories
Ops Development Stories
Essential kubectl Commands for Efficient Kubernetes Management

Get logs of the previous container

kubectl -n my-namespace logs my-pod --previous

Sort pods by creation timestamp (descending)

kubectl get pods --sort-by=.metadata.creationTimestamp

Sort pods by creation timestamp (ascending)

kubectl get pods --sort-by=.metadata.creationTimestamp | awk 'NR == 1; NR > 1 {print $0 | "tac"}'
kubectl get pods --sort-by=.metadata.creationTimestamp | tail -n +2 | tac
kubectl get pods --sort-by={metadata.creationTimestamp} --no-headers | tac
kubectl get pods --sort-by=.metadata.creationTimestamp | tail -n +2 | tail -r

Show QoS class of pods across all namespaces

kubectl get pods --all-namespaces -o custom-columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace,QOS-CLASS:.status.qosClass

Copy a Secret to another namespace

kubectl get secrets -o json --namespace namespace-old | \
  jq '.items[].metadata.namespace = "namespace-new"' | \
  kubectl create -f -

Retrieve Kubernetes token

kubectl -n kube-system describe $(kubectl -n kube-system get secret -n kube-system -o name | grep namespace) | grep token

Clean evicted, error, or completed pods

# clean Evicted
kubectl get pods --all-namespaces -o wide | grep Evicted | awk '{print $1,$2}' | xargs -L1 kubectl delete pod -n 
# clean error
kubectl get pods --all-namespaces -o wide | grep Error | awk '{print $1,$2}' | xargs -L1 kubectl delete pod -n 
# clean completed
kubectl get pods --all-namespaces -o wide | grep Completed | awk '{print $1,$2}' | xargs -L1 kubectl delete pod -n

Force‑delete pods in "Terminating" state within a specific namespace

kubectl get pod -n $namespace | grep Terminating | awk '{print $1}' | xargs kubectl delete pod --grace-period=0 --force

Force‑delete all "Terminating" pods across the cluster

for ns in $(kubectl get ns --no-headers | cut -d ' ' -f1); do \
  for po in $(kubectl -n $ns get po --no-headers --ignore-not-found | grep Terminating | cut -d ' ' -f1); do \
    kubectl -n $ns delete po $po --force --grace-period 0; \
  done; \
done;

Export clean YAML (requires kubectl‑neat plugin)

# needs plugin kubectl-neat https://github.com/itaysk/kubectl-neat
kubectl get cm nginx-config -oyaml | kubectl neat -o yaml

Clean unused PersistentVolumes (PVs)

kubectl describe -A pvc | grep -E "^Name:.*$|^Namespace:.*$|^Used By:.*$" | grep -B 2 "<none>" | grep -E "^Name:.*$|^Namespace:.*$" | cut -f2 -d: | paste -d " " - - | xargs -n2 bash -c 'kubectl -n ${1} delete pvc ${0}'

Delete unbound PVCs

kubectl get pvc --all-namespaces | tail -n +2 | grep -v Bound | awk '{print $1,$2}' | xargs -L1 kubectl delete pvc -n

Temporarily stop pods in a namespace (scale to zero)

# Method 1: patch deployments
kubectl get deploy -o name -n <NAMESPACE> | xargs -I{} kubectl patch {} -p '{"spec":{"replicas":0}}'

# Method 2: scale deployments
kubectl get deploy -o name | xargs -I{} kubectl scale --replicas=0 {}

Temporarily disable a DaemonSet

kubectl patch daemonsets nginx-ingress-controller -p '{"spec":{"template":{"spec":{"nodeSelector":{"project/xdp":"none"}}}}}'

Delete unbound PVs

kubectl get pv | tail -n +2 | grep -v Bound | awk '{print $1}' | xargs -L1 kubectl delete pv

Sort pods by restart count

kubectl get pods -A --sort-by='.status.containerStatuses[0].restartCount'

Zero‑downtime restart of Deployments, DaemonSets, StatefulSets

kubectl -n <namespace> rollout restart deployment <deployment-name>

Find container by overlay2 directory name

docker ps -q | xargs docker inspect --format '{{.Name}}, {{.State.Pid}}, {{.Id}}, {{.GraphDriver.Data.WorkDir}}'

List bound ports of a container

docker inspect --format '{{/*通过变量组合展示容器绑定端口列表*/}}已绑定端口列表:{{println}}{{range $p,$conf := .NetworkSettings.Ports}}{{$p}} -> {{(index $conf 0).HostPort}}{{println}}{{end}}' Web_web_1

Show containers in a network or indicate none

docker inspect --format '{{range .Containers}}{{.Name}}{{println}}{{else}}With No Containers{{end}}' bridge

Read default gateway from network index

docker inspect bridge --format '{{/*查看网络的默认网关*/}}{{(index IPAM.Config 0).Gateway}}'

Check if a container has a restart policy

docker ps -q | xargs docker inspect --format '{{if not .State.Restarting}}{{.Name}}容器没有配置重启策略{{end}}'

Show container current status

docker inspect --format '{{or .State.Status .State.Restarting}}' configuration-center

Display IP addresses of all containers

docker inspect --format='{{range NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -q)

Display MAC addresses of all containers

docker inspect --format='{{range NetworkSettings.Networks}}{{.MacAddress}}{{end}}' $(docker ps -a -q)

List container names without leading slash

docker inspect --format='{{.Name}}' $(docker ps -aq) | cut -d"/" -f2

Create an ephemeral, interactive pod

kubectl run ephemeral-busybox \
  --rm \
  --stdin \
  --tty \
  --restart=Never \
  --image=lqshow/busybox-curl:1.28 \
  -- sh

Get container log path

docker inspect --format='{{.LogPath}}' docker-test1

Debug CoreDNS

kubectl run -it --rm --restart=Never --image=infoblox/dnstools:latest dnstools

View node resource usage

kubectl get nodes --no-headers | awk '{print $1}' | xargs -I {} sh -c "echo {} ; kubectl describe node {} | grep Allocated -A 5 | grep -ve Event -ve Allocated -ve percent -ve --;"

Show total node resources

kubectl get no -o=custom-columns="NODE:.metadata.name,ALLOCATABLE CPU:.status.allocatable.cpu,ALLOCATABLE MEMORY:.status.allocatable.memory"

Show CPU allocation per node

kubectl get nodes --no-headers | awk '{print $1}' | xargs -I {} sh -c 'echo -n "{}\t"|tr "
" " " ; kubectl describe node {} | grep Allocated -A 5 | grep -ve Event -ve Allocated -ve percent -ve  | grep cpu | awk "{print $2 $3}"'

Show memory allocation per node

kubectl get nodes --no-headers | awk '{print $1}' | xargs -I {} sh -c 'echo "{}\t"|tr "
" " " ; kubectl describe node {} | grep Allocated -A 5 | grep -ve Event -ve Allocated -ve percent -ve  | grep memory | awk "{print $2 $3}"'

List all images used by pods

kubectl get pods -o custom-columns='NAME:metadata.name,IMAGES:spec.containers[*].image'

Count threads (example command)

printf "    ThreadNUM  PID\t\tCOMMAND
" && ps -eLf | awk '{ $1=null;$3=null;$4=null;$5=null;$6=null;$7=null;$8=null;$9=null;print}' | sort | uniq -c | sort -rn | head -10

Set environment variable on a deployment

kubectl set env deploy <DEPLOYMENT_NAME> OC_XXX_HOST=bbb

Port‑forward localhost to a pod

kubectl port-forward nginx-po 3000:80

Port‑forward localhost to a service

kubectl port-forward svc/nginx-web 3201

Configure default StorageClass

kubectl patch storageclass <your-class-name> -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'

Run a command in multiple pods

kubectl get pods -o name | xargs -I{} kubectl exec {} -- <command goes here>

Get container name from a pod

kubectl get po calibre-web-76b9bf4d8b-2kc5j -o json | jq -j ".spec.containers[].name"

Enter a container's namespace

docker ps | grep APP_NAME
docker inspect CONTAINER_ID | grep Pid
nsenter -t PID -n

Find non‑running pods

kubectl get pods -A --field-selector=status.phase!=Running | grep -v Complete

List nodes with memory capacity

kubectl get no -o json | jq -r '.items | sort_by(.status.capacity.memory)[] | [.metadata.name,.status.capacity.memory] | @tsv'

Exec into a pod matching a label

# Example 1
kubectl exec -i -t $(kubectl get pod -l <KEY>=<VALUE> -o name | sed 's/pods\///') -- bash

# Example 2
kubectl exec -i -t $(kubectl get pod -l <KEY>=<VALUE> -o jsonpath='{.items[0].metadata.name}') -- bash

Count pods per node

kubectl get po -o json --all-namespaces | jq '.items | group_by(.spec.nodeName) | map({"nodeName": .[0].spec.nodeName, "count": length}) | sort_by(.count)'

Copy a secret to another namespace

kubectl get secret <SECRET-NAME> -n <SOURCE-NAMESPACE> -oyaml | sed "/namespace:/d" | kubectl apply --namespace=<TARGET-NAMESPACE> -f -

Reset a cluster node

# 1. Mark node unschedulable
kubectl cordon <NODE-NAME>
# 2. Drain node (ignore daemonsets)
kubectl drain <NODE-NAME> --delete-local-data --force --ignore-daemonsets
# 3. Delete node
kubectl delete node <NODE-NAME>
# 4. Reset node (run on the node itself)
kubeadm reset
CLIcloud-nativeKubernetesDevOpscluster managementkubectl
Ops Development Stories
Written by

Ops Development Stories

Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.