PART 2: ADVANCED CONCEPTS
7. Probes
Kubernetes uses probes to know when containers are healthy. Getting them right is critical.
The Three Probe Types
| Probe | Purpose | On Failure |
| Startup | Wait for slow-starting apps | Kill and restart container |
| Liveness | Detect stuck containers | Kill and restart container |
| Readiness | Detect temporarily unable to serve | Remove 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
| Mechanism | Description |
| httpGet | HTTP GET request to a path |
| tcpSocket | TCP connection to a port |
| exec | Run a command; exit 0 = success |
| grpc | gRPC 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
| Parameter | Purpose | Default |
| initialDelaySeconds | Wait before first probe | 0 |
| periodSeconds | Time between probes | 10 |
| timeoutSeconds | Probe timeout | 1 |
| failureThreshold | Failures before action | 3 |
| successThreshold | Successes before Ready | 1 |
| terminationGracePeriodSeconds | Grace period on kill | Inherited |
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
| Pattern | Use Case |
| Dependency check | DB, cache, message queue |
| Cache warmup | Wait for warm cache |
| Feature flag | Disable traffic for maintenance |
| Circuit breaker | Shed 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
| Probe | Do | Don't |
| Startup | Use for slow starts | Use as liveness |
| Liveness | Check container only | Check external deps |
| Readiness | Check dependencies | Check container health |
| All | Set timeoutSeconds | Use default (1s) if app is slow |
| All | Test in staging | Copy 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
| Property | Init Container | Main Container |
| Run order | Sequential | Parallel |
| Run frequency | Once | Continuous |
| Runs on restart | Yes | Yes |
| Lifecycle | Must complete | Runs forever |
| Supports probes | ❌ | ✅ |
| Supports lifecycle hooks | ❌ | ✅ |
Common Init Container Patterns
| Pattern | Purpose |
| Wait for dependency | Block until DB is ready |
| Clone repo | Pre-populate volumes |
| Setup config | Generate config from templates |
| Migrations | Run DB migrations |
| Download assets | Fetch 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-Pattern | Why It's Bad |
| Long-running work | Delays Pod readiness |
| External dependencies | Fragile |
| Network calls | Slow, might fail |
| Heavy computation | Should be a Job |
| No retry logic | Init 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:
| Problem | Impact |
| Restart order | Sidecars might terminate before main container |
| Readiness | Sidecar readiness blocks Pod readiness |
| Lifecycle | No control over start order |
| Job completion | Sidecar 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
| Aspect | Regular Sidecar | Native Sidecar |
| Defined as | Container | Init container with restartPolicy: Always |
| Start order | Parallel | Before main containers |
| Termination order | Parallel | After main containers |
| Ready state | Blocks Pod Ready | Doesn't block Pod Ready |
| Job completion | Keeps Job alive | Terminates with Job |
| Probes | Supports probes | Supports probes |
When to Use Native Sidecars
| Use Case | Why |
| Log shipping | Must not terminate before app |
| Service mesh proxy | Must be ready before app |
| Metric exporters | Must not block Pod readiness |
| Jobs with sidecars | Must 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:
log-shipperstarts firstappstarts after- When
appexits,log-shipperis terminated - If
log-shippercrashes, 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
| Problem | Solution |
| Distroless images have no shell | Ephemeral container with shell |
| Can't restart Pod to add debug tools | Add container in-place |
| Need to inspect a running app | Share its namespaces |
Creating an Ephemeral Container
bash
kubectl debug -it <pod> --image=busybox --target=<container>
Key flags:
--target=<container>— Share target container's namespaces--image=<image>— Which image to use-it— Interactive + TTY
What Ephemeral Containers Can See
| Namespace | Shared? |
| Network | Yes (same Pod) |
| Process | Yes (with --target) |
| IPC | Yes |
| Filesystem | No (own filesystem) |
| Cgroup | Yes |
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
| Profile | Capabilities Added |
| legacy | No extra (default) |
| general | SYS_PTRACE, SYS_CHROOT |
| baseline | NET_RAW, CAP_SYS_ADMIN subset |
| netadmin | NET_ADMIN, NET_RAW, SYS_PTRACE |
| restricted | None |
| sysadmin | All CAP_SYS_ADMIN |
Security Considerations
| Risk | Mitigation |
| Ephemeral container can read Pod data | RBAC restrict pods/ephemeralcontainers |
| Network access | Same network; use NetworkPolicies |
| No removal | Only Pod deletion |
| Persistence | Ephemeral (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:
- Pod is marked Terminating
- Kubernetes removes Pod from Service endpoints
preStoprunssleep 15(blocking)- Load balancers see the endpoint removal
- After 15 seconds, SIGTERM is sent to the app
- 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
| Practice | Why |
| Use sleep 5-15s | Allow endpoint propagation |
| Keep it short | Delays Pod termination |
| Handle SIGTERM in app | Finish in-flight requests |
| Match terminationGracePeriodSeconds | Ensure 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
| Value | Use Case |
| 0 | Immediate kill (no graceful) |
| 10 | Fast shutdown |
| 30 | Default |
| 60-120 | Long-running request handling |
| 300+ | Batch jobs with checkpointing |
The SIGTERM Handling Contract
Your app must:
- Catch SIGTERM
- Stop accepting new requests
- Finish in-flight requests
- Close resources (DB connections, file handles)
- Exit cleanly (exit 0)
Language-specific patterns:
| Language | Pattern |
| Go | signal.NotifyContext |
| Python | signal.signal(SIGTERM, handler) |
| Node.js | process.on('SIGTERM', handler) |
| Java | Runtime.getRuntime().addShutdownHook |
| Rust | tokio::signal::ctrl_c |
Zero-Downtime Shutdown Checklist
- ✅ App handles SIGTERM
- ✅ preStop hook with sleep
- ✅ terminationGracePeriodSeconds long enough
- ✅ Readiness probe goes false during shutdown
- ✅ Multiple replicas
- ✅ Graceful connection draining
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:
- Leave orphaned resources
- Cause data corruption
- Skip preStop hooks
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:
- Node drain can evict all replicas
- Cluster upgrade can take down your service
- Autoscaler scale-down can cause outages
With PDB:
- Minimum available is guaranteed
- Disruptions are throttled
- Availability is protected
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
| Setting | Behavior | When |
| minAvailable | Absolute minimum pods | Simpler reasoning |
| maxUnavailable | Maximum pods that can be down | More flexible |
Formula: minAvailable = replicas - maxUnavailable
For 3 replicas:
minAvailable: 2=maxUnavailable: 1minAvailable: 1=maxUnavailable: 2
Percentage-Based
yaml
spec:
minAvailable: 50% # Keep 50% available
Scales with replica count.
Voluntary vs Involuntary Disruptions
| Type | Example | PDB Protects? |
| Voluntary | kubectl drain, rolling update | ✅ Yes |
| Involuntary | Node 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
| Practice | Why |
| Set PDB for every HA app | Prevent accidental outages |
| Use pod anti-affinity | Spread replicas |
Use minAvailable | Easier to reason |
| Match replicas + 1 | Ensure disruptions possible |
Test with kubectl drain | Verify 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
| Class | Conditions | Eviction Priority |
| Guaranteed | requests == limits (CPU + memory) | Last |
| Burstable | requests < limits | Middle |
| BestEffort | No requests/limits | First |
QoS Affects Restart Behavior
When a node is under memory pressure:
- BestEffort Pods killed first
- Burstable Pods using > requests killed next
- 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
| Workload | QoS Target | Why |
| Database | Guaranteed | Cannot be evicted |
| Web API | Burstable | Can burst, protects against leaks |
| Batch job | Burstable | Can run BestEffort if cheap |
| Debug pod | BestEffort | Temporary |
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):
| Class | Value | Purpose |
system-cluster-critical | 2000000000 | Cluster components |
system-node-critical | 2000001000 | Node components |
system-critical | 2000000000 | (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:
- Scheduler finds low-priority Pods on a candidate node
- Evicts them
- 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.