Stage 4, Part 2 of 9 · p. 30, Workloads & Lifecycle Deep Dive

PART 2: ADVANCED CONCEPTS

7. Probes

Kubernetes uses probes to know when containers are healthy. Getting them right is critical.

The Three Probe Types

ProbePurposeOn Failure
StartupWait for slow-starting appsKill and restart container
LivenessDetect stuck containersKill and restart container
ReadinessDetect temporarily unable to serveRemove from Service endpoints

The Lifecycle Interaction

text
Pod starts
    │
    ▼
Startup probe runs
    │
    ├── Succeeds → Liveness + Readiness start
    │
    └── Fails → Container restarted

Key insight: Startup probes disable liveness and readiness until they succeed. This prevents premature kills of slow-starting apps.

Probe Mechanisms

MechanismDescription
httpGetHTTP GET request to a path
tcpSocketTCP connection to a port
execRun a command; exit 0 = success
grpcgRPC health check (K8s 1.24+)

HTTP Probe

yaml
livenessProbe:
  httpGet:
    path: /healthz
    port: 8080
    httpHeaders:
    - name: Custom-Header
      value: Awesome
  initialDelaySeconds: 10
  periodSeconds: 10
  timeoutSeconds: 2
  failureThreshold: 3
  successThreshold: 1

TCP Probe

yaml
livenessProbe:
  tcpSocket:
    port: 5432
  initialDelaySeconds: 15
  periodSeconds: 20

Use for: Databases, message queues, any TCP service without HTTP.

Exec Probe

yaml
livenessProbe:
  exec:
    command:
    - /bin/sh
    - -c
    - "pg_isready -U postgres"
  initialDelaySeconds: 30
  periodSeconds: 10

Use for: Complex health checks, custom logic.

gRPC Probe (K8s 1.24+)

yaml
livenessProbe:
  grpc:
    port: 50051
    service: my-service
  initialDelaySeconds: 10
  periodSeconds: 10

Requires gRPC Health Checking Protocol support in the app.

Probe Parameters

ParameterPurposeDefault
initialDelaySecondsWait before first probe0
periodSecondsTime between probes10
timeoutSecondsProbe timeout1
failureThresholdFailures before action3
successThresholdSuccesses before Ready1
terminationGracePeriodSecondsGrace period on killInherited

The Liveness Probe Anti-Pattern

DON'T make liveness probes dependent on external services:

yaml
# BAD: Database dependency in liveness
livenessProbe:
  httpGet:
    path: /healthz  # Checks DB connection

Why it's bad: If the database hiccups, all Pods die simultaneously. This causes cascading failures.

Correct approach: Liveness should only check this container is alive. External dependencies belong in readiness.

yaml
# GOOD: Liveness checks self
livenessProbe:
  httpGet:
    path: /live    # "Am I running?"
  periodSeconds: 10

# GOOD: Readiness checks dependencies
readinessProbe:
  httpGet:
    path: /ready   # "Can I serve traffic?"

Readiness Probe Patterns

PatternUse Case
Dependency checkDB, cache, message queue
Cache warmupWait for warm cache
Feature flagDisable traffic for maintenance
Circuit breakerShed load when overwhelmed

Startup Probe Tuning

For slow-starting apps:

yaml
startupProbe:
  httpGet:
    path: /healthz
    port: 8080
  failureThreshold: 30          # 30 attempts
  periodSeconds: 10             # every 10 seconds
  # = up to 300 seconds (5 min) for startup

After startup succeeds, liveness and readiness probes begin.

Probe Best Practices

ProbeDoDon't
StartupUse for slow startsUse as liveness
LivenessCheck container onlyCheck external deps
ReadinessCheck dependenciesCheck container health
AllSet timeoutSecondsUse default (1s) if app is slow
AllTest in stagingCopy from examples

The Probe Debugging Workflow

bash
# Check probe failures
kubectl describe pod <pod> | grep -A3 "Liveness\|Readiness\|Startup"

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

# Test the probe manually
kubectl exec -it <pod> -- curl -v http://localhost:8080/healthz

8. Init Containers

Init containers run before main containers. They run sequentially, each must complete before the next.

Init Container Characteristics

PropertyInit ContainerMain Container
Run orderSequentialParallel
Run frequencyOnceContinuous
Runs on restartYesYes
LifecycleMust completeRuns forever
Supports probes❌✅
Supports lifecycle hooks❌✅

Common Init Container Patterns

PatternPurpose
Wait for dependencyBlock until DB is ready
Clone repoPre-populate volumes
Setup configGenerate config from templates
MigrationsRun DB migrations
Download assetsFetch models, datasets

Example: Wait for Database

yaml
spec:
  initContainers:
  - name: wait-for-db
    image: busybox:1.36
    command:
    - sh
    - -c
    - |
      until nc -z postgres 5432; do
        echo "Waiting for postgres..."
        sleep 2
      done
      echo "Postgres is ready"
  containers:
  - name: app
    image: myapp:1.0

Example: Setup Config from Template

yaml
spec:
  initContainers:
  - name: setup-config
    image: busybox:1.36
    command:
    - sh
    - -c
    - |
      cat > /config/app.yaml <<EOF
      database:
        host: ${DB_HOST}
        port: ${DB_PORT}
      EOF
    env:
    - name: DB_HOST
      value: postgres
    - name: DB_PORT
      value: "5432"
    volumeMounts:
    - name: config
      mountPath: /config
  containers:
  - name: app
    image: myapp:1.0
    volumeMounts:
    - name: config
      mountPath: /etc/app
  volumes:
  - name: config
    emptyDir: {}

Init Container Failure

If an init container fails, the Pod is restarted (based on restartPolicy). Logs from failed init containers are available via:

bash
kubectl logs <pod> -c <init-container-name>

Init Container Anti-Patterns

Anti-PatternWhy It's Bad
Long-running workDelays Pod readiness
External dependenciesFragile
Network callsSlow, might fail
Heavy computationShould be a Job
No retry logicInit containers fail fast

9. Native Sidecar Containers (K8s 1.29+)

Sidecar containers are containers that run alongside the main container to provide auxiliary functionality (logging, proxying, syncing).

Traditional Sidecar Problems

Before K8s 1.29, sidecars were regular containers. This caused issues:

ProblemImpact
Restart orderSidecars might terminate before main container
ReadinessSidecar readiness blocks Pod readiness
LifecycleNo control over start order
Job completionSidecar keeps Job alive

Native Sidecar Containers

Kubernetes 1.29 introduced native sidecars as a special type of init container with restartPolicy: Always.

yaml
spec:
  initContainers:
  - name: log-shipper
    image: fluent/fluent-bit:latest
    restartPolicy: Always              # ← This makes it a sidecar
    volumeMounts:
    - name: logs
      mountPath: /var/log
  containers:
  - name: app
    image: myapp:1.0
    volumeMounts:
    - name: logs
      mountPath: /var/log
  volumes:
  - name: logs
    emptyDir: {}

Key Differences

AspectRegular SidecarNative Sidecar
Defined asContainerInit container with restartPolicy: Always
Start orderParallelBefore main containers
Termination orderParallelAfter main containers
Ready stateBlocks Pod ReadyDoesn't block Pod Ready
Job completionKeeps Job aliveTerminates with Job
ProbesSupports probesSupports probes

When to Use Native Sidecars

Use CaseWhy
Log shippingMust not terminate before app
Service mesh proxyMust be ready before app
Metric exportersMust not block Pod readiness
Jobs with sidecarsMust terminate with Job

The Log Shipper Example

yaml
spec:
  initContainers:
  - name: log-shipper
    image: fluent/fluent-bit:2.2
    restartPolicy: Always
    volumeMounts:
    - name: varlog
      mountPath: /var/log
    resources:
      limits:
        cpu: 100m
        memory: 128Mi
  containers:
  - name: app
    image: myapp:1.0
    volumeMounts:
    - name: varlog
      mountPath: /var/log

Behavior:

  1. log-shipper starts first
  2. app starts after
  3. When app exits, log-shipper is terminated
  4. If log-shipper crashes, it restarts

10. Ephemeral Containers

Ephemeral containers are temporary containers added to a running Pod for debugging. They can't be removed (only Pod deletion removes them).

Why Ephemeral Containers

ProblemSolution
Distroless images have no shellEphemeral container with shell
Can't restart Pod to add debug toolsAdd container in-place
Need to inspect a running appShare its namespaces

Creating an Ephemeral Container

bash
kubectl debug -it <pod> --image=busybox --target=<container>

Key flags:

What Ephemeral Containers Can See

NamespaceShared?
NetworkYes (same Pod)
ProcessYes (with --target)
IPCYes
FilesystemNo (own filesystem)
CgroupYes

The Debug Workflow

bash
# 1. Pod is misbehaving
kubectl get pods
# myapp-abc123   1/1   Running   (but not responding)

# 2. Add ephemeral container with network tools
kubectl debug -it myapp-abc123 --image=nicolaka/netshoot --target=myapp

# 3. Inside, inspect network
netstat -tulpn          # What's listening?
ss -s                    # Connection summary
tcpdump -i any port 8080 # What's on the wire?
ps aux                   # What's running?
cat /proc/1/cmdline      # What's the main process?
ls /proc/1/root/         # Main container's filesystem

# 4. Exit (container remains until Pod is deleted)
exit

Debug Profiles

bash
kubectl debug <pod> --image=busybox --profile=netadmin
ProfileCapabilities Added
legacyNo extra (default)
generalSYS_PTRACE, SYS_CHROOT
baselineNET_RAW, CAP_SYS_ADMIN subset
netadminNET_ADMIN, NET_RAW, SYS_PTRACE
restrictedNone
sysadminAll CAP_SYS_ADMIN

Security Considerations

RiskMitigation
Ephemeral container can read Pod dataRBAC restrict pods/ephemeralcontainers
Network accessSame network; use NetworkPolicies
No removalOnly Pod deletion
PersistenceEphemeral (dies with Pod)

RBAC for ephemeral containers:

yaml
- apiGroups: [""]
  resources: ["pods/ephemeralcontainers"]
  verbs: ["update"]

Restrict this to debugging roles, not app teams.


11. Container Lifecycle Hooks

Lifecycle hooks let containers react to lifecycle events: PostStart and PreStop.

PostStart

Runs immediately after container starts (but no guarantee it runs before ENTRYPOINT).

yaml
containers:
- name: app
  image: myapp:1.0
  lifecycle:
    postStart:
      exec:
        command: ["/bin/sh", "-c", "echo Started at $(date) >> /var/log/lifecycle.log"]

Important: PostStart runs in parallel with the container's entrypoint. It's not a blocking gate.

PreStop

Runs before container is terminated, blocking the SIGTERM until it completes.

yaml
containers:
- name: app
  image: myapp:1.0
  lifecycle:
    preStop:
      exec:
        command: ["/bin/sh", "-c", "sleep 10"]

The PreStop Sleep Pattern

The most common production pattern:

yaml
lifecycle:
  preStop:
    exec:
      command: ["/bin/sh", "-c", "sleep 15"]

Why it works:

  1. Pod is marked Terminating
  2. Kubernetes removes Pod from Service endpoints
  3. preStop runs sleep 15 (blocking)
  4. Load balancers see the endpoint removal
  5. After 15 seconds, SIGTERM is sent to the app
  6. App handles SIGTERM gracefully

The race condition: If the app receives SIGTERM before the load balancer removes it from endpoints, in-flight requests fail. The preStop sleep gives time for endpoint propagation.

HTTP PreStop

yaml
lifecycle:
  preStop:
    httpGet:
      path: /drain
      port: 8080

Tells the app to stop accepting new connections and drain.

PreStop Best Practices

PracticeWhy
Use sleep 5-15sAllow endpoint propagation
Keep it shortDelays Pod termination
Handle SIGTERM in appFinish in-flight requests
Match terminationGracePeriodSecondsEnsure preStop completes

The terminationGracePeriodSeconds Relationship

yaml
spec:
  terminationGracePeriodSeconds: 30
  containers:
  - name: app
    lifecycle:
      preStop:
        exec:
          command: ["sh", "-c", "sleep 15"]   # 15s of the 30s budget

If preStop doesn't finish within terminationGracePeriodSeconds, the container is SIGKILL'd.


12. Graceful Shutdown and Termination

for gs is to makesure pod not immedialy kill the pod but give time to shutdown and finish its process while sending sigterm shutdown and it have period we can set in yaml file and if it still running will force kill it with sigkill

The Termination Flow

When a Pod is deleted:

text
1. Pod marked for deletion (deletionTimestamp set)
   │
   ▼
2. Endpoints controller removes Pod from Service endpoints
   │
   ▼
3. PreStop hook runs (blocks)
   │
   ▼
4. SIGTERM sent to container PID 1
   │
   ▼
5. Wait up to terminationGracePeriodSeconds
   │
   ▼
6. If still running, SIGKILL
   │
   ▼
7. Pod removed from API server

terminationGracePeriodSeconds

yaml
spec:
  terminationGracePeriodSeconds: 30     # Default: 30
ValueUse Case
0Immediate kill (no graceful)
10Fast shutdown
30Default
60-120Long-running request handling
300+Batch jobs with checkpointing

The SIGTERM Handling Contract

Your app must:

  1. Catch SIGTERM
  2. Stop accepting new requests
  3. Finish in-flight requests
  4. Close resources (DB connections, file handles)
  5. Exit cleanly (exit 0)

Language-specific patterns:

LanguagePattern
Gosignal.NotifyContext
Pythonsignal.signal(SIGTERM, handler)
Node.jsprocess.on('SIGTERM', handler)
JavaRuntime.getRuntime().addShutdownHook
Rusttokio::signal::ctrl_c

Zero-Downtime Shutdown Checklist

The "Force Delete" Anti-Pattern

bash
# DON'T DO THIS in production
kubectl delete pod <pod> --force --grace-period=0

This bypasses graceful termination. It can:

Only use force-delete for genuinely stuck Pods (e.g., node is gone).


13. Pod Disruption Budgets

A PodDisruptionBudget (PDB) limits how many Pods can be voluntarily disrupted at once.

for pdb is how many we keep pod keep running this purpose is to prevent pod under our needs, by setting minavaliable and max unavailable, to makesure pod keep running under visible budget and if any distruption happen it will makesure recreate in other node to keep same budget

Why PDBs Matter

Without PDB:

With PDB:

PDB Configuration

yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: web-pdb
spec:
  minAvailable: 2                # Always keep 2 pods available
  selector:
    matchLabels:
      app: web

Or use maxUnavailable:

yaml
spec:
  maxUnavailable: 1              # Only 1 pod can be unavailable
  selector:
    matchLabels:
      app: web

minAvailable vs maxUnavailable

SettingBehaviorWhen
minAvailableAbsolute minimum podsSimpler reasoning
maxUnavailableMaximum pods that can be downMore flexible

Formula: minAvailable = replicas - maxUnavailable

For 3 replicas:

Percentage-Based

yaml
spec:
  minAvailable: 50%    # Keep 50% available

Scales with replica count.

Voluntary vs Involuntary Disruptions

TypeExamplePDB Protects?
Voluntarykubectl drain, rolling update✅ Yes
InvoluntaryNode crash, OOMKill❌ No

PDB only protects against voluntary disruptions. Node failures ignore PDBs.

The PDB Deadlock

Problem: If PDB requires minAvailable: 2 and only 2 replicas exist, no node can be drained.

text
Node-1: web-1, web-2, web-3
Node-2: (empty)

PDB: minAvailable: 2

# Try to drain node-1:
# Removing web-1 → 2 available ✅
# Removing web-2 → 1 available ❌ (blocks)

Solution: Ensure replicas are spread across nodes:

yaml
affinity:
  podAntiAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
    - labelSelector:
        matchLabels:
          app: web
      topologyKey: kubernetes.io/hostname

PDB Best Practices

PracticeWhy
Set PDB for every HA appPrevent accidental outages
Use pod anti-affinitySpread replicas
Use minAvailableEasier to reason
Match replicas + 1Ensure disruptions possible
Test with kubectl drainVerify PDB works

Testing PDBs

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

# Try to drain a node
kubectl drain node-1 --ignore-daemonsets

# If PDB blocks, you'll see errors

14. Resource Management and QoS

We covered resources in Stage 1. Here's the workload-specific view.

QoS Classes

ClassConditionsEviction Priority
Guaranteedrequests == limits (CPU + memory)Last
Burstablerequests < limitsMiddle
BestEffortNo requests/limitsFirst

QoS Affects Restart Behavior

When a node is under memory pressure:

  1. BestEffort Pods killed first
  2. Burstable Pods using > requests killed next
  3. Guaranteed Pods killed last

Guaranteed Workload

yaml
resources:
  requests:
    cpu: 1000m
    memory: 1Gi
  limits:
    cpu: 1000m
    memory: 1Gi

Best for: Databases, critical workloads.

Burstable Workload

yaml
resources:
  requests:
    cpu: 100m
    memory: 128Mi
  limits:
    cpu: 1000m
    memory: 1Gi

Best for: Most web apps, APIs.

BestEffort Workload

yaml
# No resources section

Best for: Nothing production. Only dev/test.

QoS in Practice

WorkloadQoS TargetWhy
DatabaseGuaranteedCannot be evicted
Web APIBurstableCan burst, protects against leaks
Batch jobBurstableCan run BestEffort if cheap
Debug podBestEffortTemporary

15. Pod Overhead and Priority

Pod Overhead

Pod Overhead accounts for resources consumed by the Pod infrastructure (not the containers).

yaml
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:
  name: kata-containers
overhead:
  podFixed:
    cpu: 250m
    memory: 160Mi
handler: kata

When a Pod uses this RuntimeClass, Kubernetes adds these overheads to scheduling calculations.

Use cases: VM-based runtimes (Kata, gVisor) with sandbox overhead.

Priority Classes

PriorityClass influences scheduling and preemption.

yaml
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
  name: high-priority
value: 1000000
globalDefault: false
description: "For critical services"

System priority classes (built-in):

ClassValuePurpose
system-cluster-critical2000000000Cluster components
system-node-critical2000001000Node components
system-critical2000000000(older)

Using Priority

yaml
spec:
  priorityClassName: high-priority
  containers:
  - name: critical-api
    image: myapi:1.0

Preemption

When a high-priority Pod can't schedule:

  1. Scheduler finds low-priority Pods on a candidate node
  2. Evicts them
  3. Schedules the high-priority Pod

Preemption is disruptive. Use priority classes carefully.


16. Advanced Deployment Patterns

Blue/Green Deployments

Two identical environments, switch traffic atomically.

yaml
# Blue (current)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-blue
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
      version: blue
  template:
    metadata:
      labels:
        app: web
        version: blue
    spec:
      containers:
      - name: web
        image: web:1.0
---
# Green (new)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-green
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
      version: green
  template:
    metadata:
      labels:
        app: web
        version: green
    spec:
      containers:
      - name: web
        image: web:2.0
---
# Service (points to blue initially)
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
    version: blue     # Switch to "green" for cutover
  ports:
  - port: 80

Cutover: Change the Service selector from blue to green.

Rollback: Change it back.

Canary Deployments

Deploy a small percentage of traffic to the new version.

Option 1: Two Deployments + Service

yaml
# Stable (9 replicas)
metadata:
  name: web-stable
spec:
  replicas: 9
---
# Canary (1 replica)
metadata:
  name: web-canary
spec:
  replicas: 1
---
# Service selects BOTH
spec:
  selector:
    app: web          # No version selector

Traffic distribution: 9:1 (90% stable, 10% canary).

Option 2: Service Mesh (Istio)

yaml
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: web
spec:
  hosts:
  - web
  http:
  - route:
    - destination:
        host: web
        subset: stable
      weight: 90
    - destination:
        host: web
        subset: canary
      weight: 10

Progressive Delivery

Combine canary with metrics analysis:

yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: web
spec:
  replicas: 5
  strategy:
    canary:
      steps:
      - setWeight: 10
      - pause: {duration: 5m}
      - setWeight: 25
      - pause: {duration: 5m}
      - setWeight: 50
      - pause: {duration: 5m}
      - setWeight: 100

Argo Rollouts automates this with Prometheus analysis.


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