Stage 4, Part 6 of 9, Workloads & Lifecycle Deep Dive

Text

PART 6: HANDS-ON LABS

Lab 1: Master Deployment Strategies

Goal: Practice rolling update, rollback, and paused deployments.

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

# Verify
kubectl get deployment web -o wide
kubectl rollout status deployment/web

# Update with rolling strategy
kubectl set image deployment/web nginx=nginx:1.25-alpine
kubectl rollout status deployment/web -w

# View history
kubectl rollout history deployment/web

# Rollback
kubectl rollout undo deployment/web
kubectl rollout status deployment/web

# Pause → make multiple changes → resume
kubectl rollout pause deployment/web
kubectl set image deployment/web nginx=nginx:1.26-alpine
kubectl set resources deployment/web --limits=cpu=500m,memory=256Mi
kubectl set env deployment/web VERSION=2.0
kubectl rollout resume deployment/web
kubectl rollout status deployment/web -w

# Restart (rolling restart)
kubectl rollout restart deployment/web

# Cleanup
kubectl delete deployment web

Lab 2: Build a StatefulSet with Stable Identity

Goal: Deploy a StatefulSet and verify stable identity.

bash
# Create Headless Service and StatefulSet
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Service
metadata:
  name: web-headless
spec:
  clusterIP: None
  selector:
    app: web-stateful
  ports:
  - port: 80
    name: web
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: web-headless
  replicas: 3
  selector:
    matchLabels:
      app: web-stateful
  template:
    metadata:
      labels:
        app: web-stateful
    spec:
      containers:
      - name: nginx
        image: nginx:1.25-alpine
        ports:
        - containerPort: 80
        volumeMounts:
        - name: data
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 100Mi
EOF

# Watch Pods start in order
kubectl get pods -l app=web-stateful -w

# Verify stable DNS
kubectl run test --image=busybox --rm -it --restart=Never -- nslookup web-0.web-headless
kubectl run test --image=busybox --rm -it --restart=Never -- nslookup web-1.web-headless

# Write to each Pod's unique storage
kubectl exec web-0 -- sh -c "echo 'Pod 0' > /usr/share/nginx/html/index.html"
kubectl exec web-1 -- sh -c "echo 'Pod 1' > /usr/share/nginx/html/index.html"

# Delete a Pod and verify its storage persists
kubectl delete pod web-0
kubectl wait --for=condition=Ready pod/web-0 --timeout=60s
kubectl exec web-0 -- cat /usr/share/nginx/html/index.html
# Should still be "Pod 0"

# Cleanup
kubectl delete statefulset web
kubectl delete svc web-headless
kubectl delete pvc -l app=web-stateful

Lab 3: Deploy a DaemonSet

Goal: Deploy a DaemonSet and verify it runs on all nodes.

bash
# Create a simple DaemonSet
cat <<'EOF' | kubectl apply -f -
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: node-logger
spec:
  selector:
    matchLabels:
      app: node-logger
  template:
    metadata:
      labels:
        app: node-logger
    spec:
      tolerations:
      - operator: Exists
      containers:
      - name: logger
        image: busybox:1.36
        command: ["sh", "-c", "while true; do echo $(hostname) $(date); sleep 30; done"]
        resources:
          limits:
            cpu: 50m
            memory: 32Mi
          requests:
            cpu: 10m
            memory: 16Mi
EOF

# Verify one Pod per node
kubectl get pods -l app=node-logger -o wide
kubectl get nodes

# Check logs
kubectl logs -l app=node-logger --tail=2

# Cleanup
kubectl delete daemonset node-logger

Lab 4: Tune Probes

Goal: Configure all three probe types.

bash
# Create a Pod with all three probes
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: probe-test
spec:
  containers:
  - name: app
    image: kennethreitz/httpbin
    ports:
    - containerPort: 80
    startupProbe:
      httpGet:
        path: /status/200
        port: 80
      failureThreshold: 30
      periodSeconds: 2
    livenessProbe:
      httpGet:
        path: /status/200
        port: 80
      periodSeconds: 10
      timeoutSeconds: 2
      failureThreshold: 3
    readinessProbe:
      httpGet:
        path: /status/200
        port: 80
      periodSeconds: 5
      timeoutSeconds: 2
      failureThreshold: 3
EOF

# Watch state transitions
kubectl get pod probe-test -w

# Check probe status
kubectl describe pod probe-test | grep -A5 "Liveness\|Readiness\|Startup"

# Simulate probe failure (make the probe path wrong)
kubectl patch pod probe-test --type=json -p='[{"op":"replace","path":"/spec/containers/0/livenessProbe/httpGet/path","value":"/status/500"}]'

# Watch restarts
kubectl get pod probe-test -w

# Cleanup
kubectl delete pod probe-test

Lab 5: Implement Native Sidecar Containers

Goal: Use a native sidecar for log shipping.

Prerequisites: Kubernetes 1.29+.

bash
# Create Pod with native sidecar
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: sidecar-test
spec:
  initContainers:
  - name: log-shipper
    image: busybox:1.36
    restartPolicy: Always
    command: ["sh", "-c", "while true; do echo '[sidecar] tailing logs'; sleep 5; done"]
    resources:
      limits:
        cpu: 50m
        memory: 32Mi
  containers:
  - name: app
    image: busybox:1.36
    command: ["sh", "-c", "while true; do echo '[app] doing work'; sleep 3; done"]
    resources:
      limits:
        cpu: 50m
        memory: 32Mi
EOF

# Verify both containers run
kubectl get pod sidecar-test

# Check sidecar starts first
kubectl logs sidecar-test -c log-shipper --tail=5
kubectl logs sidecar-test -c app --tail=5

# Delete the app container (sidecar should keep running for a moment)
kubectl exec sidecar-test -c app -- kill 1

# Check pod restarts (sidecar shouldn't restart independently)
kubectl get pod sidecar-test

# Cleanup
kubectl delete pod sidecar-test

Lab 6: Configure Graceful Shutdown

Goal: Implement graceful shutdown with preStop.

bash
# Create Deployment with graceful shutdown
cat <<'EOF' | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
  name: graceful
spec:
  replicas: 3
  selector:
    matchLabels:
      app: graceful
  template:
    metadata:
      labels:
        app: graceful
    spec:
      terminationGracePeriodSeconds: 30
      containers:
      - name: app
        image: kennethreitz/httpbin
        ports:
        - containerPort: 80
        lifecycle:
          preStop:
            exec:
              command: ["sh", "-c", "echo 'PreStop: draining'; sleep 10"]
        readinessProbe:
          httpGet:
            path: /status/200
            port: 80
          periodSeconds: 2
EOF

# Wait for ready
kubectl wait --for=condition=Available deployment/graceful

# Watch a Pod get terminated
POD=$(kubectl get pods -l app=graceful -o jsonpath='{.items[0].metadata.name}')
echo "Deleting $POD..."
time kubectl delete pod $POD
# Should take ~10 seconds (preStop sleep)

# Cleanup
kubectl delete deployment graceful

Lab 7: Implement PodDisruptionBudgets

Goal: Create and test PDBs.

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

# Label pods
kubectl label pods -l app=web app=web

# Create a PDB
cat <<'EOF' | kubectl apply -f -
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: web-pdb
spec:
  minAvailable: 3
  selector:
    matchLabels:
      app: web
EOF

# Check PDB status
kubectl get pdb web-pdb
# NAME      MIN AVAILABLE   MAX UNAVAILABLE   ALLOWED DISRUPTIONS   AGE
# web-pdb   3               N/A               2                     5s

# Try to drain a node
kubectl get nodes
# kubectl drain <node> --ignore-daemonsets --dry-run=client

# Verify the PDB protects
kubectl describe pdb web-pdb

# Cleanup
kubectl delete pdb web-pdb
kubectl delete deployment web

Lab 8: Debug a CrashLoopBackOff

Goal: Diagnose and fix a crashlooping Pod.

bash
# Create a Pod that will crash
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: crasher
spec:
  containers:
  - name: app
    image: busybox:1.36
    command:
    - sh
    - -c
    - |
      echo "Attempting to start..."
      if [ ! -f /config/required.txt ]; then
        echo "ERROR: /config/required.txt not found"
        exit 1
      fi
      echo "Started successfully"
      sleep 3600
    volumeMounts:
    - name: config
      mountPath: /config
  volumes:
  - name: config
    configMap:
      name: missing-configmap        # This doesn't exist!
EOF

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

# Describe
kubectl describe pod crasher
# Look for CreateContainerConfigError or CrashLoopBackOff

# Check logs
kubectl logs crasher
kubectl logs crasher --previous

# Fix the missing ConfigMap
kubectl create configmap missing-configmap --from-literal=required.txt="yes"

# Delete the Pod to force recreation
kubectl delete pod crasher

# Recreate with the ConfigMap
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: crasher
spec:
  containers:
  - name: app
    image: busybox:1.36
    command:
    - sh
    - -c
    - |
      echo "Attempting to start..."
      if [ ! -f /config/required.txt ]; then
        echo "ERROR: /config/required.txt not found"
        exit 1
      fi
      echo "Started successfully"
      sleep 3600
    volumeMounts:
    - name: config
      mountPath: /config
  volumes:
  - name: config
    configMap:
      name: missing-configmap
EOF

kubectl get pod crasher

# Cleanup
kubectl delete pod crasher
kubectl delete configmap missing-configmap

Lab 9: Deploy a Complete Production Workload

Goal: Deploy a production-grade application with all best practices.

bash
# Create namespace
kubectl create namespace production

# Deploy a complete stack
cat <<'EOF' | kubectl apply -n production -f -
# ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: web-config
data:
  nginx.conf: |
    user nginx;
    worker_processes auto;
    error_log /var/log/nginx/error.log warn;
    events { worker_connections 1024; }
    http {
      include /etc/nginx/mime.types;
      default_type application/octet-stream;
      access_log /var/log/nginx/access.log;
      sendfile on;
      keepalive_timeout 65;
      server {
        listen 8080;
        location /health { return 200 "healthy\n"; }
        location / { return 200 "Hello from production!\n"; }
      }
    }
---
# Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      terminationGracePeriodSeconds: 30
      securityContext:
        runAsNonRoot: true
        runAsUser: 101
        fsGroup: 101
        seccompProfile:
          type: RuntimeDefault
      containers:
      - name: nginx
        image: nginx:1.25-alpine
        ports:
        - containerPort: 8080
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop: ["ALL"]
            add: ["NET_BIND_SERVICE", "CHOWN", "SETGID", "SETUID"]
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 500m
            memory: 256Mi
        volumeMounts:
        - name: config
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf
        - name: cache
          mountPath: /var/cache/nginx
        - name: run
          mountPath: /var/run
        startupProbe:
          httpGet:
            path: /health
            port: 8080
          failureThreshold: 30
          periodSeconds: 2
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          periodSeconds: 10
          timeoutSeconds: 2
          failureThreshold: 3
        readinessProbe:
          httpGet:
            path: /health
            port: 8080
          periodSeconds: 5
          timeoutSeconds: 2
          failureThreshold: 3
        lifecycle:
          preStop:
            exec:
              command: ["sh", "-c", "sleep 10"]
      volumes:
      - name: config
        configMap:
          name: web-config
      - name: cache
        emptyDir: {}
      - name: run
        emptyDir: {}
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchLabels:
                  app: web
              topologyKey: kubernetes.io/hostname
---
# Service
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
  ports:
  - port: 80
    targetPort: 8080
---
# PodDisruptionBudget
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: web-pdb
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app: web
---
# NetworkPolicy (default deny + allow)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: web-netpol
spec:
  podSelector:
    matchLabels:
      app: web
  policyTypes: ["Ingress"]
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: ingress-nginx
    ports:
    - port: 8080
EOF

# Verify
kubectl get all -n production
kubectl get pdb -n production
kubectl get netpol -n production

# Test
kubectl port-forward -n production svc/web 8080:80 &
sleep 2
curl http://localhost:8080
curl http://localhost:8080/health
kill %1

# Cleanup
kubectl delete namespace production

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