Overview

kubectl is the most commonly used tool for Kubernetes administrators, yet most people only use 20% of its capabilities. You type kubectl get pods -n production dozens of times a day without realizing a single alias can cut the keystrokes in half. When problems arise, you only know kubectl describe and kubectl logs, unaware that krew plugins can troubleshoot network, resource, and certificate issues with a single command. This article systematically covers the kubectl productivity toolchain — from aliases to plugins to interactive tools — to double your daily K8s operation efficiency.

References: kubectl Official Documentation, krew Official Site

I. kubectl Alias Configuration

1.1 Basic Aliases

# ~/.bashrc or ~/.zshrc

# Basic abbreviations
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kdel='kubectl delete'
alias ke='kubectl exec'
alias kl='kubectl logs'
alias kf='kubectl apply -f'
alias kdf='kubectl delete -f'
alias kr='kubectl run'

# Common resource abbreviations
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgn='kubectl get nodes'
alias kgd='kubectl get deployments'
alias kgsec='kubectl get secrets'
alias kgcm='kubectl get configmaps'
alias kging='kubectl get ingress'
alias kgns='kubectl get namespaces'
alias kgpv='kubectl get pv'
alias kgpvc='kubectl get pvc'
alias kdsa='kubectl describe sa'

# Wide output + custom columns
alias kgpw='kubectl get pods -o wide'
alias kgsw='kubectl get svc -o wide'
alias kgnw='kubectl get nodes -o wide'

# Watch mode
alias kgpw='watch -n 2 kubectl get pods -o wide'
alias kgnw='watch -n 5 kubectl get nodes -o wide'

# All namespaces
alias kgpa='kubectl get pods --all-namespaces'
alias kgsa='kubectl get svc --all-namespaces'

# YAML output
alias kgpy='kubectl get pods -o yaml'
alias kgsy='kubectl get svc -o yaml'

1.2 Advanced Aliases and Functions

# === Context and namespace quick switching ===
alias kctx='kubectl config current-context'
alias kuctx='kubectl config use-context'
alias kc='kubectl config'

# === Log-related ===
# Follow logs
alias klf='kubectl logs -f'
# Previous container logs (for post-crash troubleshooting)
alias klp='kubectl logs --previous'
# Multi-container Pod logs
klall() {
    kubectl logs "$1" --all-containers=true --tail=100
}

# === Temporary debug Pod ===
kdebug() {
    kubectl run debug-"$RANDOM" -it --rm --image=nicolaka/netshoot -- bash
}

# Start a debug Pod on a specific node
kdebug-node() {
    local node="$1"
    kubectl run debug-"$RANDOM" -it --rm --image=nicolaka/netshoot \
        --overrides='{"spec":{"nodeName":"'"$node"'","hostNetwork":true,"dnsPolicy":"ClusterFirstWithHostNet"}}' \
        -- bash
}

# === Quick exec into Pod ===
kexec() {
    local pod="$1"
    shift
    kubectl exec -it "$pod" -- "${@:-bash}"
}

# Exec into a specific container in a Pod
kexec-c() {
    local pod="$1"
    local container="$2"
    shift 2
    kubectl exec -it "$pod" -c "$container" -- "${@:-sh}"
}

# === Port forwarding ===
alias kpf='kubectl port-forward'

# Quick port-forward to a Deployment
kpfd() {
    local deployment="$1"
    local local_port="$2"
    local remote_port="${3:-$2}"
    kubectl port-forward "deployment/${deployment}" "${local_port}:${remote_port}"
}

# === Pod resource usage ===
alias ktop='kubectl top'
alias ktopp='kubectl top pods'
alias ktopn='kubectl top nodes'
alias ktoph='kubectl top pods --sort-by=cpu'

# === Rollout management ===
alias kro='kubectl rollout'
alias kros='kubectl rollout status'
alias kror='kubectl rollout restart'
alias krou='kubectl rollout undo'

# === Labels and annotations ===
alias kgl='kubectl get pods --show-labels'
alias kgla='kubectl get pods -L app,version,env'

# === Event viewing ===
alias kev='kubectl get events --sort-by=.lastTimestamp'
alias kevw='kubectl get events --watch --sort-by=.lastTimestamp'

# === Apply and rollback ===
alias kaf='kubectl apply -f'
alias kuff='kubectl diff -f'

# === Configuration management ===
alias kgsec='kubectl get secrets'
alias kgsecy='kubectl get secret -o yaml'

# Decode Secret
kdecode() {
    kubectl get secret "$1" -o jsonpath="{.data.$2}" | base64 -d
}

# === Resource cleanup ===
# Delete all Evicted Pods
kclean-evicted() {
    kubectl get pods --all-namespaces -o json | \
        jq -r '.items[] | select(.status.phase=="Failed" and .status.reason=="Evicted") | "\(.metadata.namespace) \(.metadata.name)"' | \
        xargs -r -n2 kubectl delete pod -n
}

# Delete all Completed Pods
kclean-completed() {
    kubectl get pods --all-namespaces -o json | \
        jq -r '.items[] | select(.status.phase=="Succeeded") | "\(.metadata.namespace) \(.metadata.name)"' | \
        xargs -r -n2 kubectl delete pod -n
}

# Force delete a Pod stuck in Terminating
kforce-delete() {
    kubectl delete pod "$1" --grace-period=0 --force
}

# === Quick file copy ===
kcp-from() {
    local pod="$1"
    local remote_path="$2"
    local local_path="${3:-.}"
    kubectl cp "$pod:$remote_path" "$local_path"
}

kcp-to() {
    local local_path="$1"
    local pod="$2"
    local remote_path="$3"
    kubectl cp "$local_path" "$pod:$remote_path"
}

1.3 Apply and Verify

# Reload shell configuration
source ~/.bashrc  # or source ~/.zshrc

# Verify aliases
alias | grep '^k'

# Test
k get pods
kgp
kgpw
ktopp

II. kubectx / kubens

2.1 Installation

# macOS
brew install kubectx

# Linux
git clone https://github.com/ahmetb/kubectx.git
sudo cp kubectx/kubectx /usr/local/bin/
sudo cp kubectx/kubens /usr/local/bin/

# Or install via krew
kubectl krew install ctx
kubectl krew install ns

2.2 Usage

# === kubectx: Switch contexts ===

# List all contexts
kubectx

# Switch to a specific context
kubectx production-cluster

# Switch back to the previous context
kubectx -

# Interactive selection (requires fzf)
kubectx <TAB>

# Delete a context
kubectx -d old-cluster

# === kubens: Switch namespaces ===

# List all namespaces
kubens

# Switch to a specific namespace
kubens production

# Switch back to the previous namespace
kubens -

# Interactive selection
kubens <TAB>

2.3 Aliases

# ~/.bashrc
alias kx='kubectx'
alias kn='kubens'

# Quick switch context and namespace
kprod() {
    kubectx production-cluster
    kubens production
}

kstage() {
    kubectx staging-cluster
    kubens staging
}

kdev() {
    kubectx dev-cluster
    kubens default
}

# Display current context and namespace (for prompt)
k8s_prompt() {
    local ctx ns
    ctx=$(kubectl config current-context 2>/dev/null || echo "none")
    ns=$(kubectl config view --minify -o jsonpath='{..namespace}' 2>/dev/null || echo "default")
    echo "[${ctx}:${ns}]"
}

# Integrate into PS1
# PS1='$(k8s_prompt)\w\$ '

III. k9s Interactive Tool

3.1 Installation

# macOS
brew install k9s

# Linux
curl -sS https://webinstall.dev/k9s | bash

# Or download the binary
curl -L https://github.com/derailed/k9s/releases/latest/download/k9s_Linux_amd64.tar.gz | \
    tar xz -C /usr/local/bin k9s

3.2 Common Shortcuts

ShortcutFunction
?Show help
:Enter command mode
/Filter search
EscGo back
qQuit
EnterView details
lView logs
sEnter Pod shell
eEdit resource
dDescribe
Ctrl+dDelete resource
Shift+:Switch namespace
Ctrl+aShow all namespaces

3.3 Common Command Modes

# Launch k9s
k9s

# Specify namespace
k9s -n production

# Specify context
k9s --context production-cluster

# Enter a specific resource view directly
k9s -c pods       # Pod view
k9s -c svc        # Service view
k9s -c deploy     # Deployment view
k9s -c nodes      # Node view
k9s -c jobs       # Job view
k9s -c secrets    # Secret view

3.4 k9s Configuration

# ~/.config/k9s/config.yml
k9s:
  refreshRate: 2
  maxLogs: 1000
  logger:
    tail: 500
    buffer: 5000
    sinceSeconds: 300
    fullScreen: false
    textWrap: false
    showTime: false
  currentContext: production-cluster
  currentCluster: production-cluster
  clusters:
    production-cluster:
      namespace:
        active: production
        favorites:
          - production
          - kube-system
          - monitoring
      view:
        active: pods
  thresholds:
    cpu:
      critical: 90
      warn: 70
    memory:
      critical: 90
      warn: 70

3.5 Custom Aliases

# ~/.config/k9s/aliases.yml
aliases:
  pp: v1/pods
  svc: v1/services
  dep: apps/v1/deployments
  sts: apps/v1/statefulsets
  ds: apps/v1/daemonsets
  ing: networking.k8s.io/v1/ingresses
  cm: v1/configmaps
  sec: v1/secrets
  pv: v1/persistentvolumes
  pvc: v1/persistentvolumeclaims
  sa: v1/serviceaccounts
  crd: apiextensions.k8s.io/v1/customresourcedefinitions
  hr: helm.toolkit.fluxcd.io/v2beta1/helmreleases

3.6 Custom Plugins

# ~/.config/k9s/plugins.yml
plugins:
  # Run curl inside a Pod
  curl:
    shortCut: Ctrl+C
    description: Curl pod
    scopes:
      - pods
    command: kubectl
    background: false
    args:
      - exec
      - -it
      - $NAME
      - -n
      - $NAMESPACE
      - --
      - curl
      - -s
      - http://localhost:8080/health

  # Port forward
  fwd:
    shortCut: Ctrl+F
    description: Port forward
    scopes:
      - pods
    command: kubectl
    background: true
    args:
      - port-forward
      - $NAME
      - -n
      - $NAMESPACE
      - 8080:80

  # Start a debug container on a node
  debug-node:
    shortCut: Ctrl+D
    description: Debug on node
    scopes:
      - nodes
    command: kubectl
    background: false
    args:
      - debug
      - node/$NAME
      - -it
      - --image=nicolaka/netshoot

IV. kubectl Plugins (krew)

4.1 Installing krew

# Install krew
(
  set -x; cd "$(mktemp -d)" &&
  OS="$(uname | tr '[:upper:]' '[:lower:]')" &&
  ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm64\|aarch64\)/arm64/')" &&
  KREW="krew-${OS}_${ARCH}" &&
  curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/${KREW}.tar.gz" &&
  tar zxvf "${KREW}.tar.gz" &&
  ./"${KREW}" install krew
)

# Add to PATH
export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"

# Verify
kubectl krew version

4.2 Must-Have Plugin Recommendations

# Search available plugins
kubectl krew search

# === Must-have plugins ===

# ctx / ns: Quick context and namespace switching
kubectl krew install ctx
kubectl krew install ns

# whoami: Show current identity and permissions
kubectl krew install whoami

# who-can: Check who has permission to perform an action
kubectl krew install who-can

# access-matrix: Permission matrix
kubectl krew install access-matrix

# === Troubleshooting plugins ===

# diagnose: Diagnose cluster and resource issues
kubectl krew install diagnose

# debug-pod: One-click Pod debugging
kubectl krew install debug-pod

# sniff: Pod network packet capture
kubectl krew install sniff

# df-pv: View PV disk usage
kubectl krew install df-pv

# === Resource management plugins ===

# neat: Strip default fields from YAML (for exporting clean configs)
kubectl krew install neat

# sort-manifests: Sort manifests by dependency
kubectl krew install sort-manifests

# modify-secret: Auto encode/decode when editing Secrets
kubectl krew install modify-secret

# === Security plugins ===

# rbac-lookup: Look up RBAC permissions
kubectl krew install rbac-lookup

# rbac-view: RBAC visualization
kubectl krew install rbac-view

# === Productivity plugins ===

# get-all: Get all resources
kubectl krew install get-all

# tree: View resource hierarchy as a tree
kubectl krew install tree

# tail: Multi-Pod log aggregation
kubectl krew install tail

# stats: Resource statistics
kubectl krew install stats

# === Deployment plugins ===

# rollout: Enhanced rollout management
kubectl krew install rollout

# view-utilization: Resource utilization
kubectl krew install view-utilization

4.3 Plugin Usage Examples

# === ctx / ns ===
kubectl ctx production-cluster
kubectl ns monitoring

# === whoami ===
kubectl whoami
kubectl who-can create pods --namespace default

# === neat: Export clean YAML ===
kubectl get deployment myapp -o yaml | kubectl neat > myapp-clean.yaml

# === tree: View resource hierarchy ===
kubectl tree deployment myapp
# myapp (Deployment)
# ├── myapp-xxx (ReplicaSet)
# │   ├── myapp-xxx-yyy (Pod)
# │   └── myapp-xxx-zzz (Pod)

# === tail: Aggregate logs ===
kubectl tail
kubectl tail -n production
kubectl tail -l app=myapp
kubectl tail --since 5m

# === df-pv: PV disk usage ===
kubectl df-pv

# === sniff: Network packet capture ===
kubectl sniff myapp-pod -n production -o capture.pcap

# === get-all: Get all resources ===
kubectl get-all -n production

# === view-utilization: Resource utilization ===
kubectl view-utilization

# === modify-secret: Edit Secret ===
kubectl modify-secret myapp-tls -n production

# === rbac-lookup: Look up permissions ===
kubectl rbac-lookup deploy
kubectl rbac-lookup --kind serviceaccount

V. Custom Plugin Development

5.1 kubectl Plugin Mechanism

A kubectl plugin is simply an executable file placed in your PATH, named in the format kubectl-<name>. kubectl automatically recognizes it and invokes it as a subcommand:

# Create plugin directory
mkdir -p ~/.krew/bin

# A plugin is just an executable script named kubectl-<name>
cat > ~/.krew/bin/kubectl-hello << 'EOF'
#!/usr/bin/env bash
echo "Hello from kubectl plugin!"
echo "Current context: $(kubectl config current-context)"
EOF

chmod +x ~/.krew/bin/kubectl-hello

# Usage
kubectl hello
# Hello from kubectl plugin!
# Current context: production-cluster

5.2 Useful Plugin: Pod Resource Comparison

#!/usr/bin/env bash
# kubectl-resource-compare
# Compare Pod resource requests/limits with actual usage

set -euo pipefail

NAMESPACE="${NAMESPACE:-default}"

# Get resource requests and limits for all Pods
echo "Pod Resource Comparison (namespace: ${NAMESPACE})"
echo "============================================="
printf "%-30s %-10s %-15s %-15s %-15s %-15s\n" \
    "POD" "CONTAINER" "CPU REQ" "CPU LIM" "MEM REQ" "MEM LIM"
echo "---------------------------------------------"

kubectl get pods -n "$NAMESPACE" -o json | \
jq -r '
  .items[] |
  .metadata.name as $pod |
  .spec.containers[] |
  "\($pod) \(.name) \(.resources.requests.cpu // "-") \(.resources.limits.cpu // "-") \(.resources.requests.memory // "-") \(.resources.limits.memory // "-")"
' | while read -r pod container cpu_req cpu_lim mem_req mem_lim; do
    printf "%-30s %-10s %-15s %-15s %-15s %-15s\n" \
        "$pod" "$container" "$cpu_req" "$cpu_lim" "$mem_req" "$mem_lim"
done

# Show actual usage if metrics-server is installed
if kubectl top pods -n "$NAMESPACE" &>/dev/null; then
    echo ""
    echo "Actual Usage:"
    echo "============================================="
    kubectl top pods -n "$NAMESPACE"
fi

5.3 Useful Plugin: One-Click Troubleshooting

#!/usr/bin/env bash
# kubectl-troubleshoot
# One-click Pod troubleshooting information collection

set -euo pipefail

POD_NAME="$1"
NAMESPACE="${2:-default}"

if [[ -z "$POD_NAME" ]]; then
    echo "Usage: kubectl troubleshoot <pod-name> [namespace]"
    exit 1
fi

echo "============================================"
echo "Pod Troubleshooting Report: ${POD_NAME} (ns: ${NAMESPACE})"
echo "Time: $(date)"
echo "============================================"

# 1. Pod status
echo -e "\n--- Pod Status ---"
kubectl get pod "$POD_NAME" -n "$NAMESPACE" -o wide

# 2. Events
echo -e "\n--- Events ---"
kubectl get events -n "$NAMESPACE" \
    --field-selector involvedObject.name="$POD_NAME" \
    --sort-by='.lastTimestamp'

# 3. Container status
echo -e "\n--- Container Status ---"
kubectl get pod "$POD_NAME" -n "$NAMESPACE" -o json | \
jq -r '.status.containerStatuses[] | "Container: \(.name)\n  Image: \(.image)\n  Ready: \(.ready)\n  RestartCount: \(.restartCount)\n  State: \(.state | keys[0])\n  LastState: \(.lastState | keys[0] // "none")\n"'

# 4. Resource usage
echo -e "\n--- Resource Usage ---"
kubectl top pod "$POD_NAME" -n "$NAMESPACE" --containers 2>/dev/null || \
    echo "(metrics-server unavailable)"

# 5. Recent logs
echo -e "\n--- Logs (last 50 lines) ---"
kubectl logs "$POD_NAME" -n "$NAMESPACE" --tail=50 2>/dev/null || \
    echo "(Unable to fetch logs)"

# 6. Previous crash logs
echo -e "\n--- Previous Crash Logs ---"
kubectl logs "$POD_NAME" -n "$NAMESPACE" --previous --tail=30 2>/dev/null || \
    echo "(No previous crash records)"

# 7. Network info
echo -e "\n--- Network Info ---"
kubectl get pod "$POD_NAME" -n "$NAMESPACE" -o json | \
jq -r '.status | "IP: \(.podIP)\nHostIP: \(.hostIP)\n"'

# 8. Node info
NODE=$(kubectl get pod "$POD_NAME" -n "$NAMESPACE" -o jsonpath='{.spec.nodeName}')
echo -e "\n--- Node: ${NODE} ---"
kubectl describe node "$NODE" | grep -A5 "Allocated resources"

echo -e "\n============================================"
echo "Troubleshooting information collection complete"

5.4 Useful Plugin: Cluster Resource Overview

#!/usr/bin/env bash
# kubectl-cluster-summary
# Cluster resource overview

set -euo pipefail

echo "============================================"
echo "Kubernetes Cluster Overview"
echo "Time: $(date '+%Y-%m-%d %H:%M:%S')"
echo "============================================"

# Cluster info
echo -e "\n=== Cluster Info ==="
kubectl cluster-info 2>/dev/null | head -5
echo "Context: $(kubectl config current-context)"

# Node overview
echo -e "\n=== Nodes ==="
kubectl get nodes -o wide

# Node resource usage
echo -e "\n=== Node Resource Usage ==="
kubectl top nodes 2>/dev/null || echo "(metrics-server unavailable)"

# Namespace statistics
echo -e "\n=== Namespace Resource Statistics ==="
printf "%-20s %-8s %-8s %-8s %-8s %-8s\n" \
    "NAMESPACE" "PODS" "SVC" "DEPLOY" "STS" "ING"
printf "%-20s %-8s %-8s %-8s %-8s %-8s\n" \
    "---------" "----" "---" "------" "---" "---"

for ns in $(kubectl get ns -o jsonpath='{.items[*].metadata.name}'); do
    pods=$(kubectl get pods -n "$ns" -o jsonpath='{.items[*].metadata.name}' 2>/dev/null | wc -w)
    svc=$(kubectl get svc -n "$ns" -o jsonpath='{.items[*].metadata.name}' 2>/dev/null | wc -w)
    deploy=$(kubectl get deploy -n "$ns" -o jsonpath='{.items[*].metadata.name}' 2>/dev/null | wc -w)
    sts=$(kubectl get sts -n "$ns" -o jsonpath='{.items[*].metadata.name}' 2>/dev/null | wc -w)
    ing=$(kubectl get ing -n "$ns" -o jsonpath='{.items[*].metadata.name}' 2>/dev/null | wc -w)
    printf "%-20s %-8s %-8s %-8s %-8s %-8s\n" "$ns" "$pods" "$svc" "$deploy" "$sts" "$ing"
done

# Abnormal Pods
echo -e "\n=== Abnormal Pods ==="
kubectl get pods --all-namespaces \
    --field-selector=status.phase!=Running,status.phase!=Succeeded 2>/dev/null || \
    echo "(No abnormal Pods)"

# Recent events
echo -e "\n=== Recent Warning Events ==="
kubectl get events --all-namespaces \
    --field-selector type=Warning \
    --sort-by='.lastTimestamp' 2>/dev/null | tail -20

echo -e "\n============================================"

5.5 Publishing Plugins to krew

If you’ve developed a general-purpose plugin, you can submit it to the krew index for community use:

# 1. Fork the krew-index repo
git clone https://github.com/kubernetes-sigs/krew-index.git
cd krew-index

# 2. Create a plugin manifest
# plugins/<plugin-name>.yaml
cat > plugins/my-plugin.yaml << 'EOF'
apiVersion: krew.googlecontainertools.github.com/v1alpha2
kind: Plugin
metadata:
  name: my-plugin
spec:
  version: "v1.0.0"
  homepage: https://github.com/yourname/kubectl-my-plugin
  shortDescription: "One-line description"
  description: |
    Detailed description of what the plugin does.
  platforms:
    - selector:
        matchLabels:
          os: linux
          arch: amd64
      uri: https://github.com/yourname/kubectl-my-plugin/releases/download/v1.0.0/my-plugin-linux-amd64.tar.gz
      sha256: "sha256hash..."
      bin: my-plugin
    - selector:
        matchLabels:
          os: darwin
          arch: amd64
      uri: https://github.com/yourname/kubectl-my-plugin/releases/download/v1.0.0/my-plugin-darwin-amd64.tar.gz
      sha256: "sha256hash..."
      bin: my-plugin
EOF

# 3. Submit a PR
git add plugins/my-plugin.yaml
git commit -m "Add my-plugin v1.0.0"

VI. Quick Reference

6.1 Pod Troubleshooting Quick Reference

# Check Pod status
kubectl get pod <pod> -o wide
kubectl describe pod <pod>

# View container status and restart count
kubectl get pod <pod> -o jsonpath='{.status.containerStatuses[*]}' | jq .

# View logs
kubectl logs <pod>
kubectl logs <pod> -c <container>      # Specific container
kubectl logs <pod> --previous           # Previous crash logs
kubectl logs <pod> --since=1h           # Last 1 hour
kubectl logs -f <pod>                   # Follow logs

# Exec into Pod
kubectl exec -it <pod> -- bash
kubectl exec -it <pod> -c <container> -- sh

# Check Pod resource usage
kubectl top pod <pod> --containers

# View Pod YAML (including default-injected fields)
kubectl get pod <pod> -o yaml

# View Pod events
kubectl get events --field-selector involvedObject.name=<pod>

# Port forward
kubectl port-forward <pod> 8080:80

# Temporary debug Pod
kubectl run debug -it --rm --image=nicolaka/netshoot -- bash

6.2 Node Troubleshooting Quick Reference

# Node status
kubectl get nodes -o wide
kubectl describe node <node>

# Node resource usage
kubectl top node <node>

# Pods on a node
kubectl get pods --all-namespaces --field-selector spec.nodeName=<node>

# Node resource allocation
kubectl describe node <node> | grep -A 10 "Allocated resources"

# Mark node as unschedulable
kubectl cordon <node>

# Drain Pods from a node
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data

# Restore node scheduling
kubectl uncordon <node>

6.3 Network Troubleshooting Quick Reference

# Check Service and Endpoints
kubectl get svc <svc> -o wide
kubectl get endpoints <svc>

# View Endpoints details
kubectl describe endpoints <svc>

# Check Ingress
kubectl get ingress
kubectl describe ingress <ingress>

# Check NetworkPolicy
kubectl get networkpolicy

# Test network from within a Pod
kubectl exec -it <pod> -- curl -v http://<service-name>:<port>

# Check DNS
kubectl exec -it <pod> -- nslookup <service-name>
kubectl exec -it <pod> -- cat /etc/resolv.conf

# CoreDNS logs
kubectl logs -n kube-system -l k8s-app=kube-dns

6.4 Resource Management Quick Reference

# Export resource as YAML (clean version)
kubectl get deploy <name> -o yaml | kubectl neat > deploy.yaml

# Apply changes (check diff first)
kubectl diff -f deploy.yaml
kubectl apply -f deploy.yaml

# Restart Deployment
kubectl rollout restart deployment/<name>

# Check rollout status
kubectl rollout status deployment/<name>

# Rollback
kubectl rollout undo deployment/<name>
kubectl rollout undo deployment/<name> --to-revision=3

# View rollout history
kubectl rollout history deployment/<name>

# Scale
kubectl scale deployment/<name> --replicas=5
kubectl autoscale deployment/<name> --min=2 --max=10 --cpu-percent=80

# Update image
kubectl set image deployment/<name> <container>=<new-image>:<tag>

# Add label
kubectl label pod <pod> env=production
kubectl label pod <pod> env-   # Remove label

VII. Troubleshooting Tips

7.1 Pod Stuck in Pending

# 1. Check Pod events
kubectl describe pod <pod> | grep -A 10 Events

# Common causes and troubleshooting:
# - Unschedulable: Insufficient resources
kubectl get nodes -o custom-columns="NAME:.metadata.name,CPU:.status.allocatable.cpu,MEM:.status.allocatable.memory"

# - nodeSelector/Affinity mismatch
kubectl get nodes --show-labels

# - PVC Pending
kubectl get pvc
kubectl describe pvc <pvc>

# - Taints not tolerated
kubectl get nodes -o jsonpath='{.items[*].metadata.name}' | tr ' ' '\n' | \
    xargs -I{} kubectl describe node {} | grep -A5 Taints

7.2 Pod Stuck in CrashLoopBackOff

# 1. Check previous crash logs
kubectl logs <pod> --previous

# 2. Check container exit code
kubectl get pod <pod> -o jsonpath='{.status.containerStatuses[0].lastState}' | jq .

# Common exit codes:
# 0: Normal exit
# 1: Application error
# 125: Image not found
# 126: Permission denied
# 127: Command not found
# 137: OOM Killed or SIGKILL
# 139: Segfault
# 143: SIGTERM

# 3. Check for OOM
kubectl describe pod <pod> | grep -i "OOMKilled\|terminated"

# 4. Check resource limits
kubectl get pod <pod> -o jsonpath='{.spec.containers[*].resources}' | jq .

# 5. Temporary debug (override startup command)
kubectl run debug --image=<image> -it --rm --command -- sh

7.3 Service Unreachable

# 1. Check Endpoints
kubectl get endpoints <svc>
# If empty, no Pods match the selector

# 2. Check selector matching
kubectl get pods --show-labels
kubectl get svc <svc> -o jsonpath='{.spec.selector}'

# 3. Check targetPort
kubectl get svc <svc> -o jsonpath='{.spec.ports}'

# 4. Test from within a Pod
kubectl exec -it <pod> -- curl http://<svc>:<port>

# 5. Check kube-proxy
kubectl get pods -n kube-system -l k8s-app=kube-proxy
kubectl logs -n kube-system -l k8s-app=kube-proxy --tail=50

# 6. Check iptables/ipvs
kubectl exec -it <pod> -- curl -v http://<svc-ip>:<port>

Summary

The power of kubectl lies not in the commands themselves, but in the ecosystem of tools built around it. Key takeaways from this article:

  1. Aliases are zero-cost efficiency boosters: Abbreviate high-frequency commands to 2-3 characters and save countless keystrokes daily. The key isn’t memorizing all aliases, but finding your own high-frequency operation patterns and codifying them
  2. kubectx/kubens are multi-cluster essentials: In multi-cluster, multi-namespace environments, quick context and namespace switching is the most frequent operation. Without these tools, efficiency takes a massive hit
  3. k9s transforms your interaction model: From “type commands, read results” to “interactive browsing” — especially for log viewing, resource editing, and port forwarding, k9s is an order of magnitude faster than pure command-line
  4. krew is the plugin marketplace: Plugins like ctx/ns/whoami/neat/tail/tree cover 80% of daily scenarios. Installing a plugin means installing a capability — far more efficient than writing custom scripts
  5. Custom plugins fill the gaps: The kubectl plugin mechanism is incredibly simple — just an executable in your PATH. Encapsulate your team’s common troubleshooting workflows as plugins to standardize and boost efficiency
  6. Troubleshooting needs methodology: Pending → check scheduling; CrashLoop → check logs; Service → check Endpoints. Each symptom has a fixed investigation path. Codifying these paths into scripts enables even newcomers to troubleshoot quickly

Boosting kubectl productivity is not a one-time setup but a continuous optimization process. Every time you catch yourself repeatedly typing a long command, add an alias. Every time a troubleshooting workflow requires multiple steps, write a plugin. The maturity of your toolchain directly determines your efficiency ceiling in managing K8s clusters.

References & Acknowledgments

This article referenced the following materials during writing. We thank the original authors for their contributions:

  1. kubectl Official Documentation — Kubernetes Official, referenced for kubectl Official Documentation
  2. krew Official Site — Kubernetes Official, referenced for krew Official Site