Stage 2, Part 6 of 9, kubectl Mastery & Debugging

Text

PART 6: HANDS-ON LABS

Lab 1: Master the Core Command Set

Goal: Practice get, describe, logs, exec, delete.

bash
# Create a Deployment
kubectl create deployment web --image=nginx:1.25-alpine --replicas=3

# Get
kubectl get pods
kubectl get pods -o wide
kubectl get pods -o yaml | head -50
kubectl get deployments
kubectl get all

# Describe
kubectl describe pod $(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')

# Logs
kubectl logs -l app=web --tail=20

# Exec
POD=$(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')
kubectl exec -it $POD -- sh -c "hostname && cat /etc/os-release"

# Port forward
kubectl port-forward deployment/web 8080:80 &
sleep 2
curl http://localhost:8080
kill %1

# Delete
kubectl delete deployment web

Lab 2: Contexts and kubeconfig Management

Goal: Work with multiple contexts.

bash
# View current context
kubectl config current-context
kubectl config view --minify

# List all contexts
kubectl config get-contexts

# Add a fake context (for practice)
kubectl config set-context dev --cluster=kubernetes --user=kubernetes --namespace=dev

# Switch
kubectl config use-context dev

# Set namespace
kubectl config set-context --current --namespace=default

# Verify
kubectl config view --minify | grep namespace

# Delete fake context
kubectl config delete-context dev

# Switch back
kubectl config use-context kubernetes-admin@kubernetes 2>/dev/null || \
  kubectl config use-context $(kubectl config get-contexts -o name | head -1)

# If you have kubectx installed
kubectx
kubectx <context-name>
kubens
kubens <namespace>

Lab 3: JSONPath and custom-columns

Goal: Extract specific data.

bash
# Create test data
kubectl create deployment web --image=nginx:1.25-alpine --replicas=3

# Pod names
kubectl get pods -l app=web -o jsonpath='{.items[*].metadata.name}'

# Pod IPs
kubectl get pods -l app=web -o jsonpath='{.items[*].status.podIP}'

# Name + IP with formatting
kubectl get pods -l app=web -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\n"}{end}'

# Node assignment
kubectl get pods -l app=web -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.nodeName}{"\n"}{end}'

# Custom columns
kubectl get pods -l app=web -o custom-columns='NAME:.metadata.name,IP:.status.podIP,NODE:.spec.nodeName,STATUS:.status.phase'

# Images
kubectl get pods -l app=web -o custom-columns='NAME:.metadata.name,IMAGE:.spec.containers[0].image'

# Resource requests
kubectl get pods -l app=web -o custom-columns='NAME:.metadata.name,CPU:.spec.containers[0].resources.requests.cpu,MEM:.spec.containers[0].resources.requests.memory'

# With jq (more powerful)
kubectl get pods -l app=web -o json | jq '.items[] | {name: .metadata.name, node: .spec.nodeName}'

# Cleanup
kubectl delete deployment web

Lab 4: Debug a CrashLoopBackOff

Goal: Fix a crashing Pod.

bash
# Create a Pod that will crash
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: crasher
spec:
  containers:
  - name: app
    image: busybox
    command: ["sh", "-c", "echo 'starting'; exit 1"]
EOF

# Watch it crash
kubectl get pod crasher -w &
sleep 10
kill %1

# Describe (see Events)
kubectl describe pod crasher

# Logs
kubectl logs crasher
kubectl logs crasher --previous

# Exit code
kubectl get pod crasher -o jsonpath='{.status.containerStatuses[0].lastState.terminated.exitCode}'

# Fix it
kubectl delete pod crasher
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: crasher
spec:
  containers:
  - name: app
    image: busybox
    command: ["sh", "-c", "echo 'starting'; sleep 3600"]
EOF

kubectl get pod crasher
kubectl delete pod crasher

Lab 5: Debug an ImagePullBackOff

Goal: Diagnose image pull issues.

bash
# Create a Pod with a bad image
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: bad-image
spec:
  containers:
  - name: app
    image: nginx:this-tag-does-not-exist
EOF

# Check status
sleep 10
kubectl get pod bad-image

# Describe
kubectl describe pod bad-image | grep -A10 Events

# Notice the "Failed" event with the reason

# Fix it
kubectl delete pod bad-image
kubectl run good-image --image=nginx:1.25-alpine

# Check
kubectl get pod good-image

# Cleanup
kubectl delete pod good-image

Lab 6: Debug a Pending Pod

Goal: Diagnose scheduling failures.

bash
# Create a Pod with impossible resource requirements
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: toobig
spec:
  containers:
  - name: app
    image: nginx
    resources:
      requests:
        cpu: "1000"
        memory: 5000Gi
EOF

# Check status
kubectl get pod toobig
# Status: Pending

# Describe (see why)
kubectl describe pod toobig | grep -A10 Events

# Look for FailedScheduling with reason "Insufficient cpu/memory"

# Also try an impossible node selector
kubectl delete pod toobig
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: bad-selector
spec:
  nodeSelector:
    this-label: does-not-exist
  containers:
  - name: app
    image: nginx
EOF

kubectl describe pod bad-selector | grep -A10 Events

# Cleanup
kubectl delete pod bad-selector

Lab 7: Use kubectl debug

Goal: Debug a Pod with an ephemeral container.

bash
# Create a minimal Pod (no shell)
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: distroless-sim
spec:
  containers:
  - name: app
    image: gcr.io/distroless/static-debian12
    command: ["/bin/sh"]     # This won't work — no shell!
EOF

# This will fail because there's no /bin/sh
kubectl get pod distroless-sim

# Try to exec
kubectl exec -it distroless-sim -- sh
# Error: exec: "sh": executable file not found

# Fix: use a working distroless Pod
kubectl delete pod distroless-sim
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: distroless-app
spec:
  containers:
  - name: app
    image: gcr.io/distroless/static-debian12:nonroot
    command: ["/bin/sleep"]
    args: ["3600"]
EOF

# Exec fails
kubectl exec -it distroless-app -- sh
# Error

# kubectl debug to the rescue
kubectl debug -it distroless-app --image=busybox --target=app

# Inside, you can see the target's process namespace:
ps aux
ls /proc/1/root/
exit

# Cleanup
kubectl delete pod distroless-app

Lab 8: Build a kubectl Plugin

Goal: Create a custom kubectl plugin.

bash
# Create a plugin
sudo tee /usr/local/bin/kubectl-hello <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

if [[ "${1:-}" == "--help" ]]; then
  cat <<HELP
kubectl-hello - A demo kubectl plugin

Usage:
  kubectl hello [name]

Prints a greeting.
HELP
  exit 0
fi

NAME="${1:-World}"
echo "Hello, $NAME from a kubectl plugin!"

# Show current context
CTX=$(kubectl config current-context 2>/dev/null || echo "none")
NS=$(kubectl config view --minify -o jsonpath='{..namespace}' 2>/dev/null || echo "default")
echo "Context: $CTX  Namespace: ${NS:-default}"

# Show cluster resources summary
echo ""
echo "Cluster summary:"
echo "  Nodes:      $(kubectl get nodes --no-headers 2>/dev/null | wc -l)"
echo "  Pods:       $(kubectl get pods -A --no-headers 2>/dev/null | wc -l)"
echo "  Deployments: $(kubectl get deployments -A --no-headers 2>/dev/null | wc -l)"
EOF

sudo chmod +x /usr/local/bin/kubectl-hello

# Test it
kubectl hello
kubectl hello Alice
kubectl hello --help

# Cleanup
sudo rm /usr/local/bin/kubectl-hello

Lab 9: Debug a Full Service Outage

Goal: Simulate and debug a multi-layer outage.

bash
# Setup: Create a namespace and application
kubectl create namespace outage-test

kubectl apply -n outage-test -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 2
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
      - name: api
        image: nginx:1.25-alpine
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: api
spec:
  selector:
    app: api
  ports:
  - port: 80
    targetPort: 80
EOF

# Verify it works
kubectl get all -n outage-test
kubectl run test -n outage-test --image=busybox --rm -it --restart=Never -- wget -qO- api

# Now break it — introduce a mismatch between Service selector and Pod labels
kubectl patch service api -n outage-test -p '{"spec":{"selector":{"app":"wrong"}}}'

# Symptom: Service doesn't work
kubectl run test -n outage-test --image=busybox --rm -it --restart=Never -- wget -qO- api
# Times out

# Debugging steps:
# 1. Check Service
kubectl describe svc api -n outage-test

# 2. Check Endpoints
kubectl get endpoints api -n outage-test
# Shows <none>

# 3. Check Pods
kubectl get pods -n outage-test --show-labels

# 4. Check selector vs labels
kubectl get svc api -n outage-test -o jsonpath='{.spec.selector}'
# {"app":"wrong"}
# But Pod labels are {"app":"api"}

# 5. Fix
kubectl patch service api -n outage-test -p '{"spec":{"selector":{"app":"api"}}}'

# 6. Verify
kubectl get endpoints api -n outage-test
kubectl run test -n outage-test --image=busybox --rm -it --restart=Never -- wget -qO- api

# Cleanup
kubectl delete namespace outage-test

1:1 copy of the class Google Doc, code in code blocks.