Stage 1: Kubernetes Fundamentals (Day 0/1) — The Comprehensive Guide
PART 1: CORE THEORY
1. What is Kubernetes?
Kubernetes (K8s) is an open-source container orchestration platform originally developed by Google, now maintained by the CNCF. It automates the deployment, scaling, and management of containerized applications across a cluster of machines.
Why Kubernetes Exists
Before Kubernetes, running containers in production required:
- Manually scheduling containers onto machines
- Restarting containers when they crashed
- Load balancing across replicas
- Rolling updates without downtime
- Managing storage, secrets, and configuration
Kubernetes solves all of this with a declarative API: you describe what you want, and Kubernetes continuously works to make it true.
The Declarative Model
Imperative: "Start 3 containers on node-1"
Declarative: "I want 3 replicas of this app running at all times"
The declarative model is more powerful because Kubernetes:
- Continuously reconciles reality to match your desired state
- Recovers from failures automatically
- Provides a single source of truth for your infrastructure
The Kubernetes Guarantee
You tell Kubernetes:
- What image to run
- How many replicas
- What resources each needs
- How to expose it
Kubernetes handles:
- Scheduling onto nodes
- Health checks and restarts
- Rolling updates
- Service discovery
- Load balancing
- Scaling (with HPA)
- Secret distribution
When Kubernetes Is Overkill
| Scenario | Better Alternative |
| Single server, simple app | Docker Compose |
| Static website | Netlify, Vercel, S3+CloudFront |
| Simple scheduled jobs | Cron on a VM |
| Local development | Docker Compose, Tilt |
| Serverless functions | Lambda, Cloud Functions |
Kubernetes shines when: You have 5+ microservices, need high availability, have a team to operate it, and value portability.
2. The Kubernetes Architecture
The Two Planes
text
┌────────────────────────────────────────────────────┐
│ KUBERNETES ARCHITECTURE │
│ │
│ ┌─────────────────────────────────────────────┐ │
│ │ CONTROL PLANE (Brain) │ │
│ │ ┌─────────────┐ ┌────────────┐ │ │
│ │ │ API Server │ │ etcd │ │ │
│ │ │ (REST API) │ │ (State DB) │ │ │
│ │ └───────┬─────┘ └────────────┘ │ │
│ │ │ │ │
│ │ ┌───────┴─────┐ ┌────────────┐ │ │
│ │ │ Scheduler │ │ Controller │ │ │
│ │ │ │ │ Manager │ │ │
│ │ └─────────────┘ └────────────┘ │ │
│ └──────────────────────────┬─────────────────┘ │
│ │ │
│ │ API calls │
│ ▼ │
│ ┌─────────────────────────────────────────────┐ │
│ │ WORKER NODES (Muscle) │ │
│ │ ┌───────────────┐ ┌─────────────┐ │ │
│ │ │ kubelet │ │ kubelet │ │ │
│ │ │ kube-proxy │ │ kube-proxy │ │ │
│ │ │ container │ │ container │ │ │
│ │ │ runtime │ │ runtime │ │ │
│ │ │ Pods │ │ Pods │ │ │
│ │ └───────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────┘
Control Plane Components
| Component | Purpose |
| kube-apiserver | REST API, the front door to Kubernetes. All communication goes through it. |
| etcd | Distributed key-value store. The single source of truth for cluster state. |
| kube-scheduler | Watches for unscheduled Pods, assigns them to nodes. |
| kube-controller-manager | Runs controller loops (Deployment, ReplicaSet, Node, etc.). |
| cloud-controller-manager | Integrates with cloud providers (AWS, GCP, Azure). |
Worker Node Components
| Component | Purpose |
| kubelet | Agent on each node. Watches for Pods assigned to its node, ensures containers are running. |
| kube-proxy | Manages networking (iptables/IPVS rules for Services). |
| Container Runtime | Runs containers (containerd, CRI-O). Docker is deprecated. |
| Pods | The workloads themselves. |
The Request Flow
When you run kubectl apply -f deployment.yaml:
text
1. kubectl sends HTTP request to kube-apiserver
2. API server authenticates (who are you?)
3. API server authorizes (are you allowed?)
4. Admission controllers run (mutating → schema validation → validating)
5. Object is persisted to etcd
6. Controller Manager notices new Deployment, creates a ReplicaSet
7. ReplicaSet controller creates Pods
8. Scheduler notices unscheduled Pods, assigns them to nodes
9. kubelet on each node notices its Pods, tells runtime to start containers
10. kube-proxy updates networking for Services
The key insight: Everything is a controller watching the API server, reacting to changes.
3. Pods
A Pod is the smallest deployable unit in Kubernetes. It represents one or more containers that share the same network namespace, storage, and lifecycle.
Why Pods (Not Containers)?
Kubernetes doesn't schedule containers — it schedules Pods. A Pod is a wrapper that allows multiple containers to:
- Share a network namespace (localhost communication)
- Share volumes
- Share lifecycle (start/stop together)
A Simple Pod
yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25-alpine
ports:
- containerPort: 80
Multi-Container Pod Patterns
| Pattern | Description | Use Case |
| Sidecar | Helper container alongside main | Log shipper, proxy, watcher |
| Ambassador | Proxy to external service | Database proxy, API gateway |
| Adapter | Transform output | Metrics exporter, log formatter |
| Init Containers | Run before main containers | DB migrations, config setup |
Example: Multi-Container Pod
yaml
apiVersion: v1
kind: Pod
metadata:
name: web-with-sidecar
spec:
containers:
- name: web
image: nginx:1.25-alpine
ports:
- containerPort: 80
volumeMounts:
- name: logs
mountPath: /var/log/nginx
- name: log-shipper
image: fluent/fluent-bit:latest
volumeMounts:
- name: logs
mountPath: /var/log/nginx
readOnly: true
volumes:
- name: logs
emptyDir: {}
Pod Lifecycle Phases
| Phase | Meaning |
| Pending | Pod accepted, waiting for scheduling or image pull |
| Running | At least one container running |
| Succeeded | All containers completed successfully |
| Failed | At least one container failed |
| Unknown | State couldn't be determined |
Container States
| State | Meaning |
| Waiting | Not started yet (pulling image, waiting for dependency) |
| Running | Executing |
| Terminated | Finished or crashed |
Common Waiting Reasons
| Reason | Meaning |
| ContainerCreating | Runtime is setting up the container |
| CrashLoopBackOff | Container keeps crashing and restarting |
| ImagePullBackOff | Can't pull the image |
| ErrImagePull | Image pull error (usually auth) |
| CreateContainerConfigError | Invalid config (missing ConfigMap/Secret) |
Pod Restart Policy
| Policy | Behavior |
| Always | Restart on any exit (default) |
| OnFailure | Restart only on non-zero exit |
| Never | Never restart |
When to Use Pods Directly
Almost never. Pods are ephemeral — if a node dies, the Pod is gone. Use higher-level controllers (Deployments, StatefulSets) that manage Pods for you.
Exception: Debugging, one-shot jobs, or as templates for other controllers.
4. Deployments
A Deployment is a controller that manages a set of ReplicaSets, which in turn manage Pods. It provides declarative updates, rolling updates, and rollbacks.
The Controller Hierarchy
text
Deployment
│
└── ReplicaSet (v1)
├── Pod
├── Pod
└── Pod
When you update a Deployment, it creates a new ReplicaSet and gradually scales it up while scaling the old one down.
A Deployment
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25-alpine
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
Rolling Update Strategy
| Parameter | Meaning | Default |
| maxSurge | How many extra Pods during update | 25% |
| maxUnavailable | How many Pods can be unavailable | 25% |
Zero-downtime formula:
text
replicas >= maxUnavailable + 1
For replicas: 3, maxUnavailable: 0, maxSurge: 1:
- Old Pods: 3 → 2 → 1 → 0
- New Pods: 0 → 1 → 2 → 3
- Total during update: 3 → 4 → 4 → 4 → 3
- No moment with fewer than 3 ready Pods.
Rollback
bash
# View history
kubectl rollout history deployment/nginx
# Rollback to previous
kubectl rollout undo deployment/nginx
# Rollback to specific revision
kubectl rollout undo deployment/nginx --to-revision=2
# Watch rollout
kubectl rollout status deployment/nginx
# Pause/resume rollout
kubectl rollout pause deployment/nginx
kubectl rollout resume deployment/nginx
Common Deployment Commands
bash
# Create
kubectl create deployment nginx --image=nginx:1.25-alpine --replicas=3
# Scale
kubectl scale deployment nginx --replicas=5
# Update image
kubectl set image deployment/nginx nginx=nginx:1.26-alpine
# Apply changes
kubectl apply -f deployment.yaml
# Rollout status
kubectl rollout status deployment/nginx
# Describe
kubectl describe deployment nginx
# View
kubectl get deployments
kubectl get rs
kubectl get pods -l app=nginx
The Revision History
Every Deployment change creates a new revision. Kubernetes keeps the last 10 revisions by default (revisionHistoryLimit: 10).
The Zero-Downtime Checklist
For a Deployment to be truly zero-downtime:
- ✅ Readiness probes — Kubernetes knows when a Pod is ready
- ✅ maxUnavailable: 0 — Never drop below desired replicas
- ✅ Graceful shutdown — Pods handle SIGTERM, finish in-flight requests
- ✅ preStop hooks — Delay before SIGTERM
- ✅ PodDisruptionBudgets — Protect against voluntary disruptions
- ✅ Multiple replicas — At least 2, ideally 3+
5. Services
Pods are ephemeral — their IPs change. A Service provides a stable virtual IP and DNS name that routes to a set of Pods (selected by labels).
Why Services?
| Problem | Service Solution |
| Pod IPs change | Stable ClusterIP + DNS name |
| Need load balancing | Service distributes across Pods |
| Cross-pod communication | Service discovery via DNS |
| External access | NodePort, LoadBalancer |
The Four Service Types
| Type | Accessibility | Use Case |
| ClusterIP | Internal only | Default, service-to-service |
| NodePort | Via node IP + port | Development, on-prem |
| LoadBalancer | Cloud LB | Production external access |
| ExternalName | DNS alias | External services |
ClusterIP (Default)
yaml
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: ClusterIP
selector:
app: nginx
ports:
- port: 80
targetPort: 8080
protocol: TCP
port: Port the Service listens ontargetPort: Port on the Pod to forward to
NodePort
yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-nodeport
spec:
type: NodePort
selector:
app: nginx
ports:
- port: 80
targetPort: 8080
nodePort: 30080
Accessible via <NodeIP>:30080. NodePorts range from 30000–32767 by default.
LoadBalancer
yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-lb
spec:
type: LoadBalancer
selector:
app: nginx
ports:
- port: 80
targetPort: 8080
Provisions a cloud load balancer (AWS ELB, GCP LB, etc.).
ExternalName
yaml
apiVersion: v1
kind: Service
metadata:
name: external-db
spec:
type: ExternalName
externalName: my-db.aws.rds.amazonaws.com
DNS-only. No proxying. Pods that call external-db get a CNAME to the external service.
Headless Services
clusterIP: None returns Pod IPs directly instead of a VIP. Used for StatefulSets where each Pod needs a stable identity.
yaml
apiVersion: v1
kind: Service
metadata:
name: db-headless
spec:
clusterIP: None
selector:
app: postgres
ports:
- port: 5432
Service DNS
Every Service gets a DNS name:
text
<service>.<namespace>.svc.cluster.local
Example: nginx.default.svc.cluster.local
Inside a Pod:
nginx— same namespacenginx.default— cross-namespacenginx.default.svc.cluster.local— FQDN
Port Forwarding for Debugging
bash
# Forward local port 8080 to Service port 80
kubectl port-forward svc/nginx 8080:80
# Forward to a specific Pod
kubectl port-forward pod/nginx-abc123 8080:80
Common Service Commands
bash
# List
kubectl get svc
kubectl get svc -A
# Describe
kubectl describe svc nginx
# Get endpoints (backing Pods)
kubectl get endpoints nginx
# Port forward
kubectl port-forward svc/nginx 8080:80
The Service → Endpoints Flow
- Service selects Pods via labels
- Kubernetes creates Endpoints objects (list of Pod IPs)
- kube-proxy programs iptables/IPVS rules
- Traffic to Service ClusterIP is load-balanced to Endpoints
bash
# Check endpoints
kubectl get endpoints nginx
# NAME ENDPOINTS AGE
# nginx 10.244.1.5:80,10.244.2.8:80,10.244.3.2:80 5m
Empty endpoints = Service can't find Pods. Common issue: wrong labels.
6. ConfigMaps
ConfigMaps hold non-sensitive configuration data as key-value pairs. They decouple configuration from container images, letting you change config without rebuilding.
Creating a ConfigMap
From YAML:
yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
app.properties: |
log.level=INFO
server.port=8080
cache.enabled=true
DATABASE_HOST: db.example.com
DATABASE_PORT: "5432"
From literal values:
bash
kubectl create configmap app-config \
--from-literal=DATABASE_HOST=db.example.com \
--from-literal=DATABASE_PORT=5432
From files:
bash
kubectl create configmap app-config --from-file=config.properties
Consuming ConfigMaps
As environment variables:
yaml
spec:
containers:
- name: app
image: myapp:1.0
env:
- name: DATABASE_HOST
valueFrom:
configMapKeyRef:
name: app-config
key: DATABASE_HOST
# Or inject all keys as env vars
envFrom:
- configMapRef:
name: app-config
As volume mounts:
yaml
spec:
containers:
- name: app
image: myapp:1.0
volumeMounts:
- name: config
mountPath: /etc/config
readOnly: true
volumes:
- name: config
configMap:
name: app-config
With this pattern, each key becomes a file in /etc/config/.
ConfigMap Update Behavior
| Consumption | Auto-updates? |
| Env vars | ❌ No (requires Pod restart) |
| Volumes | ✅ Yes (within ~60s) |
ConfigMap Best Practices
| Practice | Why |
| Use volumes for dynamic config | Auto-updates |
| Use env vars for static config | Simpler, no file I/O |
| Version control ConfigMaps | GitOps |
| Don't store secrets | Use Secrets instead |
| One ConfigMap per app | Easier management |
| Use Helm/Kustomize for templating | Avoid hardcoding |
ConfigMap Size Limit
The total size of a ConfigMap (and Secret) is 1 MB. For larger configs, use a volume, an init container to download, or a ConfigMap-referencing sidecar.
7. Secrets
Secrets are like ConfigMaps but for sensitive data (passwords, tokens, keys, certificates).
How Secrets Differ from ConfigMaps
| Aspect | ConfigMap | Secret |
| Data encoding | Plain text | Base64 |
| Encryption at rest | Optional | Optional (but commonly enabled) |
| Size limit | 1 MB | 1 MB |
| Use case | Non-sensitive config | Passwords, tokens, keys |
| Mount behavior | Same | Same |
Important: Secrets are not encrypted by default. They're base64-encoded, which is trivially decodable. Real security requires:
- Encryption at rest (etcd encryption)
- RBAC restrictions
- External secret stores (Vault, AWS Secrets Manager)
Creating a Secret
From literals:
bash
kubectl create secret generic db-secret \
--from-literal=username=admin \
--from-literal=password='S3cret!' \
--from-literal=host=db.example.com
From files:
bash
kubectl create secret generic tls-secret \
--from-file=tls.crt=./server.crt \
--from-file=tls.key=./server.key
From YAML:
yaml
apiVersion: v1
kind: Secret
metadata:
name: db-secret
type: Opaque
data:
username: YWRtaW4= # base64: admin
password: UzNjcmV0IQ== # base64: S3cret!
stringData: # Or use stringData for plaintext (auto-encoded)
host: db.example.com
Secret Types
| Type | Purpose |
| Opaque | Generic (default) |
| kubernetes.io/service-account-token | ServiceAccount tokens |
| kubernetes.io/dockercfg | Docker registry credentials (legacy) |
| kubernetes.io/dockerconfigjson | Docker registry credentials |
| kubernetes.io/basic-auth | Basic auth |
| kubernetes.io/ssh-auth | SSH credentials |
| kubernetes.io/tls | TLS certificate + key |
| bootstrap.kubernetes.io/token | Bootstrap tokens |
Consuming Secrets
As environment variables:
yaml
spec:
containers:
- name: app
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: password
As volume mounts:
yaml
spec:
containers:
- name: app
volumeMounts:
- name: secret
mountPath: /etc/secrets
readOnly: true
volumes:
- name: secret
secret:
secretName: db-secret
defaultMode: 0400
Secrets Are Not Truly Secret
By default, Secrets are stored unencrypted in etcd. Anyone with:
- Access to etcd
- Cluster admin RBAC
- Access to node's disk
...can read them.
Real Secret Management
| Approach | Description |
| Encryption at rest | Configure etcd encryption for Secrets |
| External Secrets Operator | Sync from Vault, AWS Secrets Manager, etc. |
| Sealed Secrets | Encrypt secrets in Git |
| SOPS | Encrypt secrets with cloud KMS |
| Vault Agent Injector | Inject Vault secrets into Pods |
The Docker Registry Secret
bash
kubectl create secret docker-registry regcred \
--docker-server=myregistry.example.com \
--docker-username=alice \
--docker-password=secret \
--docker-email=alice@example.com
Use it in a Pod:
yaml
spec:
imagePullSecrets:
- name: regcred
containers:
- name: app
image: myregistry.example.com/myapp:1.0
TLS Secret
For Ingress TLS, the Secret must be named kubernetes.io/tls type:
yaml
apiVersion: v1
kind: Secret
metadata:
name: tls-secret
type: kubernetes.io/tls
data:
tls.crt: <base64-cert>
tls.key: <base64-key>
PART 2: ADVANCED CONCEPTS
8. Ingress
An Ingress provides HTTP/HTTPS routing from outside the cluster to Services inside. It's the standard way to expose web applications.
Why Ingress?
Without Ingress, you need a LoadBalancer Service per app (expensive). With Ingress, you have one external IP and route to many Services by hostname/path.
Ingress Requires an Ingress Controller
Kubernetes doesn't ship with an Ingress Controller. You must install one:
| Controller | Notes |
| NGINX Ingress | Most popular, stable |
| Traefik | Modern, easy config |
| HAProxy Ingress | High performance |
| Contour | Envoy-based |
| Istio Gateway | If using Istio |
| AWS Load Balancer Controller | AWS-native (ALB) |
A Basic Ingress
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
Path Types
| Type | Behavior |
| Prefix | Match by URL path prefix |
| Exact | Match exact path only |
| ImplementationSpecific | Depends on controller |
TLS Termination
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: tls-ingress
spec:
ingressClassName: nginx
tls:
- hosts:
- app.example.com
secretName: tls-secret
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
Multiple Hosts
yaml
spec:
rules:
- host: api.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: api-service
port:
number: 80
- host: www.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
Common Ingress Annotations (NGINX)
| Annotation | Purpose |
nginx.ingress.kubernetes.io/rewrite-target | Rewrite URL path |
nginx.ingress.kubernetes.io/ssl-redirect | Force HTTPS |
nginx.ingress.kubernetes.io/proxy-body-size | Max upload size |
nginx.ingress.kubernetes.io/rate-limit | Rate limiting |
nginx.ingress.kubernetes.io/auth-type | Basic auth |
cert-manager.io/cluster-issuer | Auto TLS via cert-manager |
The Ingress Evolution: Gateway API
The Gateway API is the successor to Ingress, addressing its limitations:
- Multi-tenancy (Infrastructure vs Application)
- Role separation (ClusterAdmin vs AppDeveloper)
- More expressive routing (header matching, weights)
- Cross-namespace references
yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: web-route
spec:
parentRefs:
- name: my-gateway
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: web-service
port: 80
We'll cover Gateway API in depth in Stage 7 (Networking).
9. Namespaces
A Namespace is a logical partition of a cluster. It provides scope for names, RBAC, quotas, and policies.
Why Namespaces?
| Use Case | Benefit |
| Multi-team | Isolate teams |
| Multi-environment | dev, staging, prod in one cluster |
| Resource quotas | Limit total resources per team |
| RBAC | Restrict users to specific namespaces |
| Network policies | Isolate traffic by namespace |
Built-in Namespaces
| Namespace | Purpose |
| default | Where resources go if you don't specify |
| kube-system | Kubernetes components (kube-dns, kube-proxy) |
| kube-public | Public data (rarely used) |
| kube-node-lease | Node heartbeat leases |
Creating and Using Namespaces
bash
# Create
kubectl create namespace dev
# List
kubectl get namespaces
# Set as default for current context
kubectl config set-context --current --namespace=dev
# Use in commands
kubectl get pods -n dev
kubectl get pods --all-namespaces
YAML with Namespace
yaml
apiVersion: v1
kind: Namespace
metadata:
name: dev
---
apiVersion: v1
kind: Pod
metadata:
name: my-pod
namespace: dev
Resource Quotas
ResourceQuota limits total resource consumption per namespace.
yaml
apiVersion: v1
kind: ResourceQuota
metadata:
name: dev-quota
namespace: dev
spec:
hard:
requests.cpu: "10"
requests.memory: 20Gi
limits.cpu: "20"
limits.memory: 40Gi
persistentvolumeclaims: "10"
pods: "50"
services.loadbalancers: "2"
Effect: If a namespace reaches its quota, new resource creation fails.
LimitRange
LimitRange sets default requests/limits for Pods and containers.
yaml
apiVersion: v1
kind: LimitRange
metadata:
name: dev-limits
namespace: dev
spec:
limits:
- default:
cpu: 500m
memory: 512Mi
defaultRequest:
cpu: 100m
memory: 128Mi
type: Container
- max:
cpu: "2"
memory: 2Gi
min:
cpu: 10m
memory: 16Mi
type: Container
What Namespaces Don't Isolate
| Aspect | Isolated? |
| Names | ✅ Yes |
| RBAC | ✅ Yes |
| Resource quotas | ✅ Yes |
| Pods, Services, Deployments | ✅ Yes |
| Nodes | ❌ No (cluster-scoped) |
| PersistentVolumes | ❌ No (cluster-scoped) |
| ClusterRoles | ❌ No (cluster-scoped) |
| CRDs | ❌ No (cluster-scoped) |
| Network | ⚠️ Only with NetworkPolicies |
Important: Namespaces are a logical boundary, not a security boundary by default. You need NetworkPolicies and RBAC to make them secure.
10. Helm
Helm is the package manager for Kubernetes. It packages Kubernetes manifests into reusable Charts with template variables, so you can deploy the same application with different configurations.
Why Helm?
| Without Helm | With Helm |
| Copy-paste YAML for each environment | One chart, many values files |
| Manual versioning | Chart versions + release history |
| Painful rollbacks | helm rollback |
| No dependency management | Charts can depend on charts |
Core Concepts
| Concept | Description |
| Chart | A package (directory) of Kubernetes manifests + templates |
| Release | An instance of a chart deployed to a cluster |
| Values | Configuration variables |
| Repository | A collection of charts |
Chart Structure
text
mychart/
├── Chart.yaml # Metadata
├── values.yaml # Default values
├── templates/ # Kubernetes manifests (templated)
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── ingress.yaml
│ ├── _helpers.tpl # Helper templates
│ └── NOTES.txt # Post-install notes
├── charts/ # Subcharts (dependencies)
└── .helmignore # Files to ignore
Chart.yaml
yaml
apiVersion: v2
name: mychart
description: A Helm chart for my app
type: application
version: 1.0.0 # Chart version
appVersion: "1.0.0" # App version
values.yaml
yaml
replicaCount: 3
image:
repository: nginx
tag: "1.25-alpine"
pullPolicy: IfNotPresent
service:
type: ClusterIP
port: 80
ingress:
enabled: false
className: nginx
hosts:
- host: chart-example.local
paths:
- path: /
pathType: Prefix
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
A Templated Manifest
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "mychart.fullname" . }}
labels:
{{- include "mychart.labels" . | nindent 4 }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
{{- include "mychart.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "mychart.selectorLabels" . | nindent 8 }}
spec:
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
- containerPort: {{ .Values.service.port }}
resources:
{{- toYaml .Values.resources | nindent 10 }}
Helm Commands
bash
# Create a new chart
helm create mychart
# Template locally (see rendered output)
helm template mychart
# Install
helm install my-release ./mychart
# Install with custom values
helm install my-release ./mychart -f prod-values.yaml
# Install with --set
helm install my-release ./mychart --set replicaCount=5
# List releases
helm list
helm list -A
# Upgrade
helm upgrade my-release ./mychart
# Upgrade or install
helm upgrade --install my-release ./mychart
# Rollback
helm rollback my-release 1
# History
helm history my-release
# Uninstall
helm uninstall my-release
# Repos
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
helm search repo nginx
# Install from repo
helm install my-nginx bitnami/nginx
Helm Template Functions
| Function | Purpose |
include | Include a template |
tpl | Render a string as template |
toYaml | Convert to YAML |
nindent | Indent + newline |
default | Default value |
quote | Wrap in quotes |
required | Fail if missing |
lookup | Query cluster |
Helm Best Practices
| Practice | Why |
Use helm create as a starting point | Best-practice scaffold |
| One chart per application | Reusable, testable |
| Version charts semantically | 1.0.0, 1.1.0, 2.0.0 |
| Store charts in a repo | Artifact Hub, OCI, ChartMuseum |
Use .helmignore | Don't ship garbage |
Test with helm template before install | Catch errors early |
Use --atomic for installs | Rollback on failure |
| Use Helm Secrets or SOPS for secrets | Don't commit secrets |
Lint with helm lint | Catch issues in CI |
Helm vs Kustomize
| Aspect | Helm | Kustomize |
| Templating | Go templates | Overlays (no templating) |
| Packaging | Charts | Directories |
| Values | values.yaml | Patches |
| Ecosystem | Huge (Artifact Hub) | Native in kubectl |
| Complexity | Higher | Lower |
| Best For | Distributing apps | Configuring base manifests |
Both are valid. Many teams use Helm for third-party charts and Kustomize for their own apps.
11. Labels, Selectors, and Annotations
These three concepts are the glue of Kubernetes.
Labels
Labels are key-value pairs attached to objects for identification and selection.
yaml
metadata:
labels:
app: nginx
environment: production
version: "1.25"
tier: frontend
Rules:
- Keys: 63 chars max, alphanumeric +
-_. - Values: 63 chars max, alphanumeric +
-_. - Max 64 labels per object
Selectors
Selectors choose objects by labels.
Equality-based:
yaml
selector:
matchLabels:
app: nginx
environment: production
Set-based:
yaml
selector:
matchExpressions:
- key: environment
operator: In
values: [production, staging]
- key: tier
operator: NotIn
values: [database]
kubectl with Selectors
bash
# Equality
kubectl get pods -l app=nginx
kubectl get pods -l app=nginx,environment=production
# Set-based
kubectl get pods -l 'environment in (production,staging)'
kubectl get pods -l 'tier notin (database)'
kubectl get pods -l '!version'
Annotations
Annotations are key-value pairs for non-identifying metadata. They can't be used in selectors.
yaml
metadata:
annotations:
description: "Main web server"
maintainer: "team@example.com"
prometheus.io/scrape: "true"
prometheus.io/port: "9090"
deployment.kubernetes.io/revision: "3"
Use cases:
- Configuration for controllers (Ingress controllers, cert-manager)
- Deployment metadata
- Monitoring configuration
- Documentation
Labels vs Annotations
| Aspect | Labels | Annotations |
| Used in selectors | ✅ Yes | ❌ No |
| Size limit | 63 chars | 256 KB total |
| Purpose | Identify and select | Store arbitrary metadata |
| Indexed by K8s | ✅ Yes | ❌ No |
Standard Label Conventions
| Label | Use |
app.kubernetes.io/name | Application name |
app.kubernetes.io/instance | Unique instance ID |
app.kubernetes.io/version | App version |
app.kubernetes.io/component | Component (e.g., web, db) |
app.kubernetes.io/part-of | Parent system |
app.kubernetes.io/managed-by | Tool (helm, kubectl) |
Example:
yaml
metadata:
labels:
app.kubernetes.io/name: nginx
app.kubernetes.io/instance: nginx-prod
app.kubernetes.io/version: "1.25"
app.kubernetes.io/component: web
app.kubernetes.io/part-of: ecommerce
app.kubernetes.io/managed-by: helm
12. Resource Requests and Limits
Resource management is foundational. Getting it wrong causes instability.
Requests vs Limits
| Aspect | Requests | Limits |
| Purpose | Guaranteed minimum | Enforced maximum |
| Scheduling | Used to find nodes | Not used |
| CPU | Guaranteed share | Throttled if exceeded |
| Memory | Guaranteed | OOMKilled if exceeded |
| QoS | Determines class | Determines class |
The Four Cases
| Case | QoS Class | Behavior |
| Requests == Limits | Guaranteed | Highest priority, best isolation |
| Requests < Limits | Burstable | Can burst, may be throttled/killed |
| No requests/limits | BestEffort | Lowest priority, first to die |
Example
yaml
spec:
containers:
- name: app
resources:
requests:
cpu: 100m # 0.1 CPU guaranteed
memory: 128Mi # 128 MiB guaranteed
limits:
cpu: 500m # Up to 0.5 CPU
memory: 256Mi # Up to 256 MiB
CPU Units
| Value | Meaning |
| 1 | 1 full CPU core |
| 500m | 0.5 core (500 millicores) |
| 100m | 0.1 core |
| 1m | 0.001 core |
Memory Units
| Value | Meaning |
| Mi | Mebibyte (1024²) |
| Gi | Gibibyte (1024³) |
| M | Megabyte (1000²) |
| G | Gigabyte (1000³) |
Always use Mi/Gi for consistency.
The Problems
No requests = unpredictable scheduling.
K8s thinks the Pod needs 0 resources. Nodes can be oversubscribed. Pods starve.
No limits = noisy neighbors.
A Pod with a memory leak can consume all node memory and kill other Pods.
Too-low limits = throttling.
Apps get CPU throttled or OOMKilled for no good reason.
Too-high limits = wasted resources.
Nodes have low utilization but can't fit more Pods.
Best Practices
| Rule | Why |
| Always set requests | Predictable scheduling |
| Set limits for memory | Prevent OOM of other Pods |
| Consider removing CPU limits | CPU is compressible; throttling hurts |
| Set requests = limits for critical apps | Guaranteed QoS |
| Start with profiling data | Don't guess |
| Use VPA to recommend values | Data-driven sizing |
| Monitor throttling | container_cpu_cfs_throttled_seconds_total |
QoS Classes in Detail
| QoS | Conditions | Priority | When Node Pressure |
| Guaranteed | requests == limits (CPU and memory) | Highest | Killed last |
| Burstable | requests < limits | Medium | Killed if using > requests |
| BestEffort | No requests/limits | Lowest | Killed first |
Eviction Order
When a node is under memory pressure:
- BestEffort Pods evicted first
- Burstable Pods exceeding requests evicted next
- Guaranteed Pods evicted last
13. StatefulSets and DaemonSets
StatefulSets
StatefulSets manage Pods with stable identities — each Pod has a persistent name, hostname, and storage.
Key differences from Deployments:
| Aspect | Deployment | StatefulSet |
| Pod name | nginx-abc123 (random) | postgres-0, postgres-1 (ordered) |
| Hostname | Random | Stable |
| Storage | Shared or none | Per-Pod PVC |
| Startup order | Parallel | Sequential (0 → 1 → 2) |
| Shutdown order | Parallel | Reverse (2 → 1 → 0) |
| Headless Service | Optional | Required |
Use cases:
- Databases (PostgreSQL, MySQL, MongoDB)
- Message queues (Kafka, RabbitMQ, NATS)
- Distributed caches (Redis Cluster, Elasticsearch)
- Any app needing stable identity + storage
Example:
yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres
replicas: 3
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:16-alpine
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: password
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: fast-ssd
resources:
requests:
storage: 100Gi
Each Pod gets its own PVC: data-postgres-0, data-postgres-1, data-postgres-2.
DaemonSets
DaemonSets ensure a Pod runs on every node (or a subset). Used for node-level services.
Use cases:
- Log collectors (Fluent Bit, Filebeat)
- Monitoring agents (Prometheus Node Exporter, Datadog)
- Networking (CNI plugins, kube-proxy)
- Storage (CSI node plugins)
- Security (Falco, Tetragon)
Example:
yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: node-exporter
spec:
selector:
matchLabels:
app: node-exporter
template:
metadata:
labels:
app: node-exporter
spec:
hostNetwork: true
hostPID: true
containers:
- name: node-exporter
image: prom/node-exporter:v1.7.0
ports:
- containerPort: 9100
DaemonSets run on control plane nodes only if they tolerate the control-plane taint.
14. Jobs and CronJobs
Jobs
A Job runs Pods to completion. Unlike Deployments (which run forever), Jobs finish.
Use cases:
- Database migrations
- Batch processing
- One-time setup tasks
Example:
yaml
apiVersion: batch/v1
kind: Job
metadata:
name: db-migrate
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: migrate
image: myapp:1.0
command: ["python", "manage.py", "migrate"]
Job parameters:
| Parameter | Purpose |
| completions | Number of successful completions |
| parallelism | Max concurrent Pods |
| backoffLimit | Retries before failure |
| activeDeadlineSeconds | Timeout |
CronJobs
A CronJob runs Jobs on a schedule (like cron).
Example:
yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: backup
spec:
schedule: "0 2 * * *" # Every day at 2 AM
concurrencyPolicy: Forbid # Don't run overlapping
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: backup
image: backup-tool:1.0
Cron schedule format:
text
┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-6, Sun=0)
│ │ │ │ │
* * * * *
Concurrency policies:
| Policy | Behavior |
| Allow | Multiple Jobs can run concurrently |
| Forbid | Skip if previous Job still running |
| Replace | Kill previous, start new |
PART 3: PRODUCTION FAILURE MODES
15. Top 10 Kubernetes Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | CrashLoopBackOff | Pod keeps restarting | App crashes on start | kubectl logs, fix app |
| 2 | ImagePullBackOff | Can't pull image | Wrong tag, auth, network | Check image, imagePullSecrets |
| 3 | OOMKilled | Exit code 137 | Memory limit exceeded | Increase limit, fix leak |
| 4 | Pending pod | Pod never schedules | No nodes with resources | Check events, add capacity |
| 5 | Service has no endpoints | Can't reach Service | Wrong labels/selector | Fix labels |
| 6 | CreateContainerConfigError | Container fails to start | Missing ConfigMap/Secret | Create the missing resource |
| 7 | Readiness probe failure | Pod not Ready | App not responding | Fix probe or app |
| 8 | PVC pending | Volume never binds | No matching PV/StorageClass | Check StorageClass |
| 9 | Ingress not routing | 404/502 | Wrong service/port | Check Ingress config |
| 10 | Node NotReady | Node unavailable | Kubelet down, disk full | SSH, check kubelet |
16. Kubernetes Debugging Runbook
"Pod Won't Start" — Step-by-Step
text
STEP 1: Check Pod status
$ kubectl get pods
$ kubectl get pods -o wide
STEP 2: Describe the Pod (best source of truth)
$ kubectl describe pod <pod>
# Look at Events section at the bottom
STEP 3: Check logs
$ kubectl logs <pod>
$ kubectl logs <pod> --previous # Previous instance if crashed
STEP 4: For CrashLoopBackOff
# Check the app's exit code
$ kubectl get pod <pod> -o jsonpath='{.status.containerStatuses[0].lastState}'
# Review logs
$ kubectl logs <pod> --previous
STEP 5: For ImagePullBackOff
$ kubectl describe pod <pod> | grep -A5 Events
# Common causes:
# - Wrong image name/tag
# - No imagePullSecrets
# - Registry unreachable
STEP 6: For Pending
$ kubectl describe pod <pod> | grep -A10 Events
# Common causes:
# - Insufficient resources
# - Node selector/affinity mismatch
# - Taints without tolerations
# - PVC not bound
STEP 7: For CreateContainerConfigError
$ kubectl describe pod <pod>
# Usually missing ConfigMap or Secret
$ kubectl get configmap <name>
$ kubectl get secret <name>
STEP 8: Exec into the Pod (if running)
$ kubectl exec -it <pod> -- sh
$ kubectl exec -it <pod> -- /bin/bash
STEP 9: Use kubectl debug for ephemeral containers
$ kubectl debug -it <pod> --image=busybox --target=<container>
STEP 10: Check events cluster-wide
$ kubectl get events --sort-by=.metadata.creationTimestamp
$ kubectl get events --field-selector involvedObject.name=<pod>
Quick Diagnostic Table
| Status | Likely Cause | Check |
| CrashLoopBackOff | App error | kubectl logs --previous |
| ImagePullBackOff | Image/auth | kubectl describe pod |
| Pending | Resources/affinity | kubectl describe pod |
| OOMKilled | Memory limit | Increase limit, check leaks |
| Readiness probe failed | App slow | Tune probe |
| Service no endpoints | Labels | kubectl get endpoints |
17. Blast Radius Analysis
What Happens When Kubernetes Fails?
| Component | Impact | Severity |
| API server down | Can't manage cluster; running Pods continue | SEV-1 |
| etcd down | Control plane can't function | SEV-1 |
| Scheduler down | New Pods stay Pending | SEV-2 |
| Controller Manager down | No reconciliation | SEV-2 |
| Node NotReady | Pods evicted after timeout | SEV-1 |
| CNI failure | Pods lose network | SEV-1 |
| DNS failure | Service discovery breaks | SEV-1 |
| Ingress down | External access fails | SEV-1 |
Mitigation Strategies
| Strategy | Implementation |
| Multi-master control plane | 3+ masters, etcd quorum |
| Multiple replicas | At least 2-3 per workload |
| PodDisruptionBudgets | Protect during disruptions |
| Anti-affinity | Spread replicas across nodes |
| Backup etcd | Regular snapshots |
| GitOps | Declarative, versioned |
| Monitoring | Prometheus, alerts |
PART 4: CAPACITY PLANNING & COST MODELING
18. Cluster Sizing Fundamentals
Node Sizing
| Workload Type | Node Size | Why |
| General apps | 4–8 vCPU, 16–32 GB | Balanced |
| Databases | 8–16 vCPU, 64–128 GB | Memory + I/O |
| ML training | GPU nodes | Specialized hardware |
| Batch | High CPU | Compute-optimized |
Cluster Sizing Formula
text
Total CPU needed = sum(pod requests) × overcommit_ratio + system_overhead
Total memory needed = sum(pod requests) × overcommit_ratio + system_overhead
overcommit_ratio for CPU: 2-4x
overcommit_ratio for memory: 1-1.5x (be conservative)
Reserved Capacity
Reserve ~10–20% for:
- Control plane components
- kubelet, kube-proxy
- DaemonSets (logging, monitoring)
- Burst headroom
19. Resource Overcommit and Cost Optimization
Overcommit Ratios
| Resource | Safe Overcommit | Risk |
| CPU | 2–4x | Throttling |
| Memory | 1–1.5x | OOMKill |
| Disk | 1x | Capacity exhaustion |
Cost Optimization Tactics
| Tactic | Savings |
| Right-size requests/limits | 20–40% |
| Use Spot/Preemptible nodes | 60–80% for interruptible |
| Bin-packing | 20–30% |
| Autoscaling | Variable |
| Reserved instances | 30–60% |
| Multi-tenancy | 30–50% |
Example: 100-Node Cluster
text
Before optimization:
100 × m5.2xlarge ($0.384/hour) = $27,648/month
Average utilization: 25%
After optimization:
Right-size: 60 nodes
Spot for batch: 20 nodes at 70% discount
Reserved for baseline: 30 nodes at 40% discount
Costs:
Baseline: 30 × $0.384 × 730 = $8,409
Spot: 20 × $0.115 × 730 = $1,679
Total: $10,088/month
Savings: $17,560/month = $210,720/year
20. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Kubernetes SLA Design
| Target | Architecture |
| 99.9% | Multi-replica Deployments, basic monitoring |
| 99.99% | Multi-AZ, PodDisruptionBudgets, anti-affinity, HA control plane |
| 99.999% | Multi-region, chaos-tested, GitOps, automated recovery |
Zero-Downtime Checklist
- ✅
maxUnavailable: 0in Deployment strategy - ✅ Readiness probes on all containers
- ✅ Graceful shutdown (SIGTERM handling)
- ✅
preStophooks for connection draining - ✅ PodDisruptionBudgets
- ✅ Pod anti-affinity for HA
- ✅ Multiple replicas (3+)
- ✅ Multi-AZ scheduling
PART 5: ARCHITECTURE & STRATEGY
21. Cluster Topology Patterns
Single Cluster (Small Teams)
text
┌─────────────────────────────────────────────────────────────┐
│ Single Cluster │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ dev ns │ │ staging ns │ │ prod ns │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
Pros: Simple, cheap.
Cons: Single point of failure, noisy neighbors.
Multi-Cluster (Production)
text
┌─────────────────────────────────────────────────────────────┐
│ Cluster: dev Cluster: staging Cluster: prod │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────┐ │
│ │ dev │ │ staging │ │ prod │ │
│ └──────────────┘ └──────────────┘ └──────────┘ │
└─────────────────────────────────────────────────────────────┘
Pros: Isolation, safer upgrades.
Cons: More overhead.
Multi-Region (Global)
text
┌─────────────────────────────────────────────────────────────┐
│ Region A Region B Region C │
│ ┌──────────────┐ ┌──────────────┐ ┌───────┐│
│ │ Cluster │ │ Cluster │ │Cluster││
│ │ (us-east) │ │ (eu-west) │ │(ap) ││
│ └──────────────┘ └──────────────┘ └───────┘│
│ │ │ │ │
│ └───────────────────────┴─────────────────────┘ │
│ Global Load Balancer │
└─────────────────────────────────────────────────────────────┘
22. Multi-Tenancy Strategy
| Model | Isolation | Best For |
| Namespaces | Logical | Internal teams |
| vCluster | Virtual clusters | Strong isolation on shared clusters |
| Separate clusters | Physical | External customers, compliance |
| Capsule | Hierarchical namespaces | Enterprise multi-tenancy |
Recommendation:
- Internal teams → Namespaces + RBAC + NetworkPolicies + ResourceQuotas
- External customers → vCluster or separate clusters
23. Compliance & Security
| Framework | K8s Requirement |
| PCI-DSS | Network segmentation, RBAC, audit logs |
| HIPAA | Encryption, audit, access controls |
| SOC2 | Change management, monitoring |
| FedRAMP | FIPS 140-2, hardened configs |
CIS Kubernetes Benchmark key items:
- Control plane hardening
- etcd encryption
- RBAC enabled
- Audit logging
- Pod Security Standards
- NetworkPolicies
- Image scanning
- No privileged containers
PART 6: HANDS-ON LABS
Lab 1: Deploy Your First Pod
Goal: Understand Pod basics.
bash
# Create a Pod
kubectl run nginx --image=nginx:1.25-alpine --port=80
# Check it
kubectl get pods
kubectl describe pod nginx
# Test with port-forward
kubectl port-forward pod/nginx 8080:80
# In another terminal:
curl http://localhost:8080
# Logs
kubectl logs nginx
# Exec
kubectl exec -it nginx -- sh
# Inside: cat /etc/nginx/nginx.conf
exit
# Cleanup
kubectl delete pod nginx
Lab 2: Deployment with Rolling Updates
Goal: Deploy, update, rollback.
bash
# Create a Deployment
kubectl create deployment web --image=nginx:1.24-alpine --replicas=3
# Watch rollout
kubectl get pods -l app=web -w
# Update the image (rolling update)
kubectl set image deployment/web nginx=nginx:1.25-alpine
# Watch rollout
kubectl rollout status deployment/web
# View history
kubectl rollout history deployment/web
# Rollback
kubectl rollout undo deployment/web
# Verify
kubectl get pods -l app=web
# Cleanup
kubectl delete deployment web
Lab 3: Expose with Services
Goal: Create ClusterIP, NodePort, and LoadBalancer Services.
bash
# Create a Deployment
kubectl create deployment nginx --image=nginx:1.25-alpine --replicas=3
# ClusterIP Service
kubectl expose deployment nginx --port=80 --target-port=80 --name=nginx-clusterip
# Test internal access
kubectl run test --image=busybox --rm -it --restart=Never -- wget -qO- nginx-clusterip
# NodePort Service
kubectl expose deployment nginx --port=80 --target-port=80 --type=NodePort --name=nginx-nodeport
# Get node port
kubectl get svc nginx-nodeport
# Access via <NodeIP>:<NodePort>
# View endpoints
kubectl get endpoints
# Cleanup
kubectl delete svc nginx-clusterip nginx-nodeport
kubectl delete deployment nginx
Lab 4: Configuration with ConfigMaps and Secrets
Goal: Inject config and secrets.
bash
# Create ConfigMap
kubectl create configmap app-config \
--from-literal=APP_MODE=production \
--from-literal=LOG_LEVEL=info
# Create Secret
kubectl create secret generic db-secret \
--from-literal=DB_USER=admin \
--from-literal=DB_PASS=secret123
# Create Pod using both
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: config-demo
spec:
containers:
- name: app
image: busybox
command: ['sh', '-c', 'sleep 3600']
envFrom:
- configMapRef:
name: app-config
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: DB_PASS
volumeMounts:
- name: config-vol
mountPath: /etc/config
readOnly: true
volumes:
- name: config-vol
configMap:
name: app-config
EOF
# Verify
kubectl exec config-demo -- env | grep -E "APP_MODE|LOG_LEVEL|DB_PASSWORD"
kubectl exec config-demo -- ls /etc/config/
kubectl exec config-demo -- cat /etc/config/APP_MODE
# Cleanup
kubectl delete pod config-demo
kubectl delete configmap app-config
kubectl delete secret db-secret
Lab 5: Ingress with TLS
Goal: Expose with Ingress and TLS.
Prerequisites: Ingress controller installed.
bash
# Create a Deployment and Service
kubectl create deployment web --image=nginx:1.25-alpine
kubectl expose deployment web --port=80
# Create TLS cert (self-signed for testing)
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout tls.key -out tls.crt \
-subj "/CN=app.example.com"
# Create TLS Secret
kubectl create secret tls web-tls --cert=tls.crt --key=tls.key
# Create Ingress
cat <<'EOF' | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
spec:
ingressClassName: nginx
tls:
- hosts:
- app.example.com
secretName: web-tls
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
EOF
# Test
kubectl get ingress
curl -k -H "Host: app.example.com" https://<ingress-ip>/
# Cleanup
kubectl delete ingress web-ingress
kubectl delete secret web-tls
kubectl delete svc web
kubectl delete deployment web
Lab 6: Namespaces and Resource Quotas
Goal: Isolate with Namespaces and enforce quotas.
bash
# Create Namespace
kubectl create namespace dev
# Apply ResourceQuota
kubectl apply -n dev -f - <<'EOF'
apiVersion: v1
kind: ResourceQuota
metadata:
name: dev-quota
spec:
hard:
requests.cpu: "4"
requests.memory: 8Gi
limits.cpu: "8"
limits.memory: 16Gi
pods: "10"
EOF
# Apply LimitRange
kubectl apply -n dev -f - <<'EOF'
apiVersion: v1
kind: LimitRange
metadata:
name: dev-limits
spec:
limits:
- default:
cpu: 500m
memory: 512Mi
defaultRequest:
cpu: 100m
memory: 128Mi
type: Container
EOF
# Create a Pod without resources (gets defaults)
kubectl run test -n dev --image=nginx:1.25-alpine
# Check resources
kubectl get pod test -n dev -o jsonpath='{.spec.containers[0].resources}'
# Try to exceed quota
kubectl run big -n dev --image=nginx --overrides='{"spec":{"containers":[{"name":"big","image":"nginx","resources":{"requests":{"memory":"20Gi"}}}]}}'
# Expected: Error
# Cleanup
kubectl delete namespace dev
Lab 7: Package with Helm
Goal: Create, install, and upgrade a Helm chart.
bash
# Create chart
helm create mychart
cd mychart
# View the structure
ls -la
# Render locally
helm template my-release .
# Install
helm install my-release . --namespace default
# Check
kubectl get all -l app.kubernetes.io/instance=my-release
# Upgrade with different values
helm upgrade my-release . --set replicaCount=5
# Check history
helm history my-release
# Rollback
helm rollback my-release 1
# Uninstall
helm uninstall my-release
# Cleanup
cd ..
rm -rf mychart
Lab 8: StatefulSet with Persistent Storage
Goal: Deploy a stateful application.
Prerequisites: StorageClass available.
bash
# Create a StatefulSet
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Service
metadata:
name: nginx-headless
spec:
clusterIP: None
selector:
app: nginx-stateful
ports:
- port: 80
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: nginx
spec:
serviceName: nginx-headless
replicas: 3
selector:
matchLabels:
app: nginx-stateful
template:
metadata:
labels:
app: nginx-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: 1Gi
EOF
# Check Pods (created in order)
kubectl get pods -l app=nginx-stateful -w
# Check PVCs
kubectl get pvc
# Test DNS
kubectl run test --image=busybox --rm -it --restart=Never -- nslookup nginx-0.nginx-headless
# Write to each Pod's storage
kubectl exec nginx-0 -- sh -c "echo 'Pod 0 data' > /usr/share/nginx/html/index.html"
kubectl exec nginx-1 -- sh -c "echo 'Pod 1 data' > /usr/share/nginx/html/index.html"
# Cleanup
kubectl delete statefulset nginx
kubectl delete svc nginx-headless
kubectl delete pvc -l app=nginx-stateful
Lab 9: Complete 3-Tier Application
Goal: Deploy a full stack.
bash
# Create the namespace
kubectl create namespace app
# Database (StatefulSet)
kubectl apply -n app -f - <<'EOF'
apiVersion: v1
kind: Secret
metadata:
name: db-secret
type: Opaque
stringData:
POSTGRES_PASSWORD: secret123
---
apiVersion: v1
kind: Service
metadata:
name: db
spec:
clusterIP: None
selector:
app: db
ports:
- port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: db
spec:
serviceName: db
replicas: 1
selector:
matchLabels:
app: db
template:
metadata:
labels:
app: db
spec:
containers:
- name: postgres
image: postgres:16-alpine
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: POSTGRES_PASSWORD
ports:
- containerPort: 5432
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
EOF
# Backend (Deployment)
kubectl apply -n app -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: kennethreitz/httpbin
ports:
- containerPort: 80
env:
- name: DB_HOST
value: db-0.db.app.svc.cluster.local
---
apiVersion: v1
kind: Service
metadata:
name: api
spec:
selector:
app: api
ports:
- port: 80
targetPort: 80
EOF
# Frontend (Deployment + Ingress)
kubectl apply -n app -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 2
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.25-alpine
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector:
app: web
ports:
- port: 80
targetPort: 80
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
spec:
ingressClassName: nginx
rules:
- host: app.local
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
EOF
# Verify
kubectl get all -n app
# Test
kubectl port-forward -n app svc/web 8080:80
curl http://localhost:8080
# Cleanup
kubectl delete namespace app
PART 7: INCIDENT MANAGEMENT
33. Kubernetes Incident Post-Mortem Template
text
INCIDENT: Production Deployment Failed - All Pods CrashLooping
DATE: 2024-01-15
DURATION: 47 minutes
SEVERITY: SEV-1
IMPACT: 100% of the API was unavailable. All user requests failed.
TIMELINE:
14:00 - Deployment web:v2.0.0 rolled out
14:01 - Alert: Pods in CrashLoopBackOff
14:03 - On-call engineer acknowledged
14:05 - Identified missing ConfigMap "app-config-v2"
14:08 - Created ConfigMap with correct values
14:10 - Pods started successfully
14:12 - Full service restored
14:47 - Incident closed
ROOT CAUSE:
The Deployment referenced a new ConfigMap "app-config-v2" that
hadn't been created yet. All pods failed to start.
LESSONS LEARNED:
1. ConfigMaps should be part of the same Helm chart as the Deployment.
2. Readiness gates should prevent bad rollouts.
3. CI should validate all resource references exist.
ACTION ITEMS:
[ ] Include all ConfigMaps in the Helm chart (Owner: Platform, Due: 2024-01-16)
[ ] Add CI validation for resource references (Owner: Platform, Due: 2024-01-20)
[ ] Configure deployment gates (Owner: SRE, Due: 2024-01-22)
34. On-Call Runbook: Pod Won't Start
text
STEP 1: Identify the pod
$ kubectl get pods -A | grep -v Running
STEP 2: Describe the pod
$ kubectl describe pod <pod> -n <namespace>
# Check the Events section
STEP 3: Check logs
$ kubectl logs <pod> -n <namespace>
$ kubectl logs <pod> -n <namespace> --previous
STEP 4: Categorize the issue
CrashLoopBackOff → App is crashing
- Check logs
- Check exit code
- Check ConfigMap/Secret refs
ImagePullBackOff → Can't pull image
- Check image name/tag
- Check imagePullSecrets
- Check registry auth
Pending → Can't schedule
- Check node resources
- Check affinity/taints
- Check PVC status
ContainerCreating (stuck) → Volume or network issue
- Check PVC/PV status
- Check CNI
CreateContainerConfigError → Bad config
- Missing ConfigMap or Secret
STEP 5: Fix or escalate
35. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | Complete outage / all pods down | 5 min | On-call + Platform + Management |
| SEV-2 | Partial outage / degraded performance | 15 min | On-call + Platform |
| SEV-3 | Single service issue | 1 hour | On-call |
| SEV-4 | Config drift / warning | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
36. Junior-Level Questions
| Question | Expected Answer |
| What is a Pod? | Smallest deployable unit, one or more containers |
| What is a Deployment? | Controller that manages ReplicaSets and Pods |
| What is a Service? | Stable network endpoint for Pods |
| What's the difference between ConfigMap and Secret? | ConfigMap = plain config, Secret = sensitive (base64) |
| What is a Namespace? | Logical partition of a cluster |
37. Mid-Level Questions
| Question | Expected Answer |
| How does a Service find Pods? | Label selectors |
| What is a headless Service? | clusterIP: None, returns Pod IPs |
| Why use StatefulSet over Deployment? | Stable identity + per-Pod storage |
| What is an Ingress? | HTTP/HTTPS routing into the cluster |
| What is Helm? | Package manager for Kubernetes |
| What is the difference between requests and limits? | Requests = guaranteed, limits = max |
38. Senior-Level Questions
| Question | Expected Answer |
| How do you debug CrashLoopBackOff? | describe, logs --previous, check exit codes |
| How do you achieve zero-downtime deployments? | maxUnavailable: 0, readiness probes, graceful shutdown |
| What's the difference between Deployment and StatefulSet? | Identity, storage, ordering |
| How do you isolate tenants in a cluster? | Namespaces + RBAC + NetworkPolicies + Quotas |
| What is QoS and why does it matter? | Guaranteed/Burstable/BestEffort, eviction priority |
39. Staff/Principal Questions
| Question | Expected Answer |
| Design a multi-tenant Kubernetes platform. | Namespaces + RBAC + NetworkPolicies + Quotas + PSS + audit |
| How do you migrate from one cluster to another? | Velero, GitOps, blue-green clusters |
| How do you choose between Deployments and StatefulSets? | Stateful → identity + storage; Deployment → stateless |
| How do you reduce Kubernetes costs by 50%? | Right-size, Spot, bin-packing, autoscaling, multi-tenancy |
| How do you enforce security across 100 teams? | Admission policies (Kyverno/OPA) + PSS + CI validation |
Summary Cheat Sheet
| Concept | Key Takeaway |
| Pod | Smallest unit. Ephemeral. Multi-container via shared net/volume. |
| Deployment | Manages ReplicaSets. Rolling updates. Rollback. |
| Service | Stable endpoint. 4 types: ClusterIP, NodePort, LoadBalancer, ExternalName. |
| ConfigMap | Non-sensitive config. Env vars or volumes. |
| Secret | Sensitive config. Base64 (not encrypted by default). |
| Ingress | HTTP routing. Requires an Ingress Controller. |
| Namespace | Logical partition. Not a security boundary by default. |
| Helm | Package manager. Charts + values + releases. |
| Labels/Selectors | The glue of K8s. |
| Requests/Limits | Requests for scheduling, limits for enforcement. |
| StatefulSet | Stable identity + per-Pod storage. |
| DaemonSet | One Pod per node. |
| Job/CronJob | Run-to-completion, scheduled. |
| QoS | Guaranteed / Burstable / BestEffort. |
| Zero-downtime | maxUnavailable: 0 + readiness + graceful shutdown. |
Stage 2: kubectl Mastery & Debugging — The Comprehensive Guide
PART 1: CORE THEORY
1. kubectl Architecture
kubectl is the command-line interface for Kubernetes. It's a client that talks to the kube-apiserver via REST.
The Request Flow
text
┌─────────────────────────────────────────────────────────────┐
│ kubectl REQUEST FLOW │
│ │
│ kubectl get pods │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Read kubeconfig │ (auth, cluster, context) │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Build HTTP │ (GET /api/v1/namespaces/default/pods) │
│ │ Request │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Send to API │ (TLS, auth token, etc.) │
│ │ Server │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Receive JSON │ │
│ │ Response │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Format for │ (table, yaml, json, etc.) │
│ │ Terminal │ │
│ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Key Facts
| Fact | Detail |
| Language | Go |
| Protocol | REST (HTTP/HTTPS) |
| Authentication | From kubeconfig (certs, tokens, exec plugins) |
| Authorization | API server enforces RBAC |
| Config location | ~/.kube/config (default) |
| Env overrides | KUBECONFIG, KUBECTL_CONTEXT, KUBECTL_NAMESPACE |
What kubectl Is Not
- Not a control plane component. You can delete kubectl; the cluster keeps running.
- Not a proxy. It's a direct client to the API server.
- Not declarative by itself. Declarative behavior comes from
kubectl apply+ server-side reconciliation.
kubectl Version
bash
kubectl version --client # Client version
kubectl version # Client + server versions
kubectl version --short # Compact output
# Best practice: client version within ±1 minor of server
Version skew policy: kubectl supports one minor version of skew (older or newer) relative to the API server.
2. kubeconfig and Contexts
kubeconfig is a YAML file that tells kubectl:
- Which cluster to talk to
- How to authenticate
- Which namespace to use
The kubeconfig Structure
yaml
apiVersion: v1
kind: Config
clusters:
- name: dev
cluster:
server: https://dev.k8s.example.com:6443
certificate-authority-data: <base64>
- name: prod
cluster:
server: https://prod.k8s.example.com:6443
certificate-authority-data: <base64>
users:
- name: alice
user:
client-certificate-data: <base64>
client-key-data: <base64>
- name: alice-prod
user:
token: <token>
contexts:
- name: dev
context:
cluster: dev
user: alice
namespace: default
- name: prod
context:
cluster: prod
user: alice-prod
namespace: default
current-context: dev
The Three Sections
| Section | Purpose |
| clusters | API server URLs and CA certs |
| users | Credentials (certs, tokens, exec plugins) |
| contexts | Combinations of cluster + user + namespace |
Managing Contexts
bash
# List contexts
kubectl config get-contexts
# Current context
kubectl config current-context
# Switch context
kubectl config use-context prod
# Rename
kubectl config rename-context old-name new-name
# Set default namespace for current context
kubectl config set-context --current --namespace=dev
# Delete a context
kubectl config delete-context prod
# View raw config
kubectl config view
kubectl config view --minify # Only current context
kubectl config view --raw # Show secrets
Multiple kubeconfig Files
bash
# Set via environment variable
export KUBECONFIG=~/.kube/config:~/.kube/config-prod
# Merge into a single file
KUBECONFIG=~/.kube/config:~/.kube/config-prod kubectl config view --flatten > ~/.kube/merged
# Use a specific file
kubectl --kubeconfig=/path/to/config get pods
Authentication Methods
| Method | Where Used |
| Client certificates | Self-managed clusters |
| Bearer tokens | ServiceAccounts, CI |
| Exec plugins | AWS (aws eks get-token), GCP, Azure |
| OIDC | Enterprise SSO |
| Basic auth | Legacy (deprecated) |
| Webhook | Custom auth |
Exec plugin example (AWS EKS):
yaml
users:
- name: arn:aws:eks:us-east-1:123456789:cluster/prod
user:
exec:
apiVersion: client.authentication.k8s.io/v1beta1
command: aws
args:
- eks
- get-token
- --cluster-name
- prod
The exec plugin runs a command that outputs a token. Tokens expire and are refreshed automatically.
Dangerous Patterns
| Pattern | Risk |
| Sharing kubeconfig files | Auditing becomes impossible |
| Committing kubeconfig to Git | Leaks credentials |
Using admin context for daily work | Too much privilege |
| Skipping context check | Running prod command in dev cluster |
Production tip: Add cluster name to your shell prompt or use kubectx/kubens for safety.
3. Imperative vs Declarative
Kubernetes supports two ways to manage resources. Knowing when to use each is a skill.
Imperative Commands
Direct actions:
bash
kubectl run nginx --image=nginx:1.25-alpine
kubectl create deployment web --image=nginx --replicas=3
kubectl expose deployment web --port=80
kubectl scale deployment web --replicas=5
kubectl delete pod nginx
kubectl set image deployment/web nginx=nginx:1.26-alpine
kubectl label pod nginx env=prod
kubectl annotate pod nginx owner=alice
Pros: Fast, one-liners, no YAML files needed.
Cons: Not reproducible, no version control, hard to review.
Declarative Commands
Apply from manifests:
bash
kubectl apply -f deployment.yaml
kubectl apply -f ./manifests/
kubectl apply -k ./kustomize/
Pros: Reproducible, version-controlled, peer-reviewable, works with GitOps.
Cons: Requires YAML files, more setup.
The Spectrum
There are actually four levels:
| Level | Example | Use Case |
| Pure imperative | kubectl run nginx --image=nginx | Quick tests, debugging |
| Imperative with output | kubectl create deployment web --image=nginx --dry-run=client -o yaml > web.yaml | Generating manifests |
| Declarative apply | kubectl apply -f web.yaml | Standard workflow |
| GitOps | Argo CD / Flux watches Git | Production standard |
The Best Practice
Use imperative for:
- Quick tests and experiments
- Debugging (creating test pods)
- Learning
- Generating YAML templates
Use declarative for:
- Everything else
- Anything that will persist
- Anything that will be reviewed
- Anything in production
The Magic of --dry-run=client -o yaml
The most powerful pattern:
bash
kubectl create deployment web \
--image=nginx:1.25-alpine \
--replicas=3 \
--dry-run=client \
-o yaml > web.yaml
This generates a clean YAML manifest from an imperative command — perfect for starting a declarative workflow.
Comparing Output
| Command | What It Does |
--dry-run=client | Only validates client-side, doesn't send to server |
--dry-run=server | Sends to server, validates server-side (admission, etc.) |
-o yaml | Outputs as YAML |
-o json | Outputs as JSON |
4. The Core Command Set
Five commands cover 80% of daily work.
kubectl get
Retrieves resources.
bash
# Basic
kubectl get pods
kubectl get deployments
kubectl get services
kubectl get nodes
kubectl get all # All common resources in current namespace
kubectl get all -A # All namespaces
# Wide output
kubectl get pods -o wide # Show node, IP, etc.
# By name
kubectl get pod nginx-abc123
# Specific namespaces
kubectl get pods -n prod
kubectl get pods --all-namespaces
# Watch (live)
kubectl get pods -w
# Sort
kubectl get pods --sort-by=.metadata.creationTimestamp
# Show labels
kubectl get pods --show-labels
# Filter by label
kubectl get pods -l app=nginx
kubectl get pods -l 'environment in (prod,staging)'
# Filter by field
kubectl get pods --field-selector status.phase=Running
kubectl get pods --field-selector spec.nodeName=node-1
kubectl describe
Detailed human-readable info, plus events.
bash
kubectl describe pod nginx-abc123
kubectl describe deployment web
kubectl describe node node-1
kubectl describe svc nginx
The value of describe: It shows Events at the bottom — the single best debugging resource.
kubectl logs
Retrieves container logs.
bash
# Basic
kubectl logs nginx-abc123
# Follow (live)
kubectl logs -f nginx-abc123
# Previous container instance
kubectl logs nginx-abc123 --previous
# Recent only
kubectl logs nginx-abc123 --tail=100
kubectl logs nginx-abc123 --since=1h
kubectl logs nginx-abc123 --since-time="2024-01-15T10:00:00Z"
# Specific container (multi-container Pod)
kubectl logs nginx-abc123 -c sidecar
# All containers
kubectl logs nginx-abc123 --all-containers
# Prefix with Pod name
kubectl logs nginx-abc123 --prefix
# Logs from all Pods matching label
kubectl logs -l app=nginx --tail=50
# Time stamps
kubectl logs nginx-abc123 --timestamps
Tip: kubectl logs -f -l app=nginx is often easier than exec-ing into individual Pods.
kubectl exec
Runs commands inside containers.
bash
# Interactive shell
kubectl exec -it nginx-abc123 -- /bin/sh
kubectl exec -it nginx-abc123 -- bash
# Single command
kubectl exec nginx-abc123 -- cat /etc/nginx/nginx.conf
kubectl exec nginx-abc123 -- env
kubectl exec nginx-abc123 -- ps aux
# Specific container
kubectl exec -it nginx-abc123 -c sidecar -- /bin/sh
# Multiple commands
kubectl exec nginx-abc123 -- sh -c "cd /app && ls -la"
kubectl delete
Removes resources.
bash
# By name
kubectl delete pod nginx-abc123
kubectl delete deployment web
kubectl delete svc nginx
# By file
kubectl delete -f deployment.yaml
# By label
kubectl delete pods -l app=nginx
# By selector
kubectl delete pods --field-selector status.phase=Failed
# Force (immediate)
kubectl delete pod nginx-abc123 --force --grace-period=0
# All in namespace
kubectl delete all --all
The Other 15% Most-Used Commands
| Command | Purpose |
kubectl apply | Apply manifests |
kubectl create | Create from imperative |
kubectl edit | Edit live resource |
kubectl patch | Partial update |
kubectl scale | Scale replicas |
kubectl set image | Update image |
kubectl rollout | Manage rollouts |
kubectl port-forward | Local port forward |
kubectl cp | Copy files |
kubectl top | Resource usage |
kubectl auth can-i | Check permissions |
kubectl explain | Built-in docs |
kubectl api-resources | Available resource types |
kubectl api-versions | Available API versions |
kubectl cluster-info | Cluster endpoint info |
5. kubectl apply vs create vs replace
This is where declarative Kubernetes gets subtle.
The Three Commands
| Command | Behavior |
| kubectl create | Create resource; fail if exists |
| kubectl replace | Replace resource entirely; must exist |
| kubectl apply | Create or update; uses 3-way merge |
The 3-Way Merge
kubectl apply compares three things:
- Last applied configuration (stored in
kubectl.kubernetes.io/last-applied-configurationannotation) - New configuration (what you're applying now)
- Live configuration (what's currently in etcd)
The result is a merge that preserves fields not in your manifest.
Example:
Original apply:
yaml
spec:
replicas: 3
template:
spec:
containers:
- name: web
image: nginx:1.24
Then someone runs kubectl edit and changes replicas to 5.
Then you re-apply with replicas: 3.
Result: replicas goes back to 3 (your manifest is source of truth). If you had removed replicas from the manifest entirely, the 5 would be preserved.
Why This Matters
| Action | Behavior |
| Field in manifest | Managed by apply |
| Field removed from manifest | Apply removes it (via 3-way merge) |
| Field added externally | Preserved unless you explicitly remove |
Server-Side Apply (SSA)
The modern alternative:
bash
kubectl apply --server-side -f deployment.yaml
Key differences:
| Aspect | Client-Side Apply | Server-Side Apply |
| Merge location | kubectl | API server |
| State storage | last-applied-configuration annotation | managedFields |
| Conflict handling | Whole-resource | Field-level |
| Multiple controllers | Hard | Easy |
| Performance | Slower (client does work) | Faster |
Server-side apply is the future. Used by Flux, Argo CD, and most modern tooling.
When to Use Which
| Scenario | Command |
| Initial creation, one-off | kubectl create |
| Complete replacement | kubectl replace (rare) |
| Day-to-day declarative | kubectl apply (client or server) |
| Multiple controllers | kubectl apply --server-side |
| CI/CD | kubectl apply --server-side or GitOps |
The Removal Trap
If you apply a manifest that removes a field, Kubernetes will remove it. But if you use create, you can't re-apply without deleting first.
Best practice: Always apply, never create (except for generating manifests).
PART 2: ADVANCED CONCEPTS
6. Output Formats
kubectl can output in many formats. Mastering these is the difference between "someone who uses kubectl" and "someone who is productive in kubectl."
The Formats
| Format | Flag | Use Case |
| Table | default | Human reading |
| Wide | -o wide | More columns |
| YAML | -o yaml | Full resource, editable |
| JSON | -o json | Machine parsing |
| Name | -o name | Just resource names |
| JSONPath | -o jsonpath='...' | Extract specific fields |
| Custom columns | -o custom-columns=... | Custom table |
| Go template | -o go-template='...' | Advanced templating |
YAML
bash
kubectl get pod nginx-abc123 -o yaml
kubectl get deployment web -o yaml > web-backup.yaml
Use for:
- Full resource inspection
- Backing up resources
- Understanding structure
JSON
bash
kubectl get pod nginx-abc123 -o json
kubectl get pod nginx-abc123 -o json | jq '.status.containerStatuses'
Use for:
- Scripting
- jq processing
- Integration with tools
Name
bash
kubectl get pods -o name
# pod/nginx-abc123
# pod/nginx-def456
# Use with other commands
kubectl get pods -o name | xargs kubectl delete
JSONPath
Extract specific fields:
bash
# Single field
kubectl get pod nginx-abc123 -o jsonpath='{.status.podIP}'
# Multiple fields
kubectl get pod nginx-abc123 -o jsonpath='{.metadata.name}{"\t"}{.status.podIP}{"\n"}'
# Loop over list
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# Loop with format
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
# Filter by field
kubectl get pods -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}'
# First item
kubectl get pod -o jsonpath='{.items[0].metadata.name}'
Common JSONPath patterns:
| Pattern | Purpose |
.metadata.name | Pod name |
.status.podIP | Pod IP |
.spec.nodeName | Node name |
.status.phase | Pod phase |
.spec.containers[*].image | All container images |
.metadata.labels | All labels |
.metadata.annotations['key'] | Specific annotation |
Custom Columns
Build your own tables:
bash
# Simple
kubectl get pods -o custom-columns=NAME:.metadata.name,IP:.status.podIP
# With headers
kubectl get pods -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,STATUS:.status.phase'
# Complex
kubectl get pods -o custom-columns='NAME:.metadata.name,IMAGE:.spec.containers[0].image,CPU:.spec.containers[0].resources.requests.cpu'
Use cases:
| Scenario | Custom Column |
| Capacity audit | NAME:.metadata.name,CPU:.spec.containers[0].resources.requests.cpu,MEM:.spec.containers[0].resources.requests.memory |
| Image audit | NAME:.metadata.name,IMAGE:.spec.containers[*].image |
| Node assignment | NAME:.metadata.name,NODE:.spec.nodeName |
| Missing limits | NAME:.metadata.name,LIMITS:.spec.containers[0].resources.limits |
Go Template
Full Go templating:
bash
kubectl get pods -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
Rarely used; JSONPath is more common.
jq Integration
For complex processing, JSON + jq is the standard:
bash
# Pods with their images
kubectl get pods -o json | jq '.items[] | {name: .metadata.name, image: .spec.containers[0].image}'
# Pods consuming > 500m CPU
kubectl get pods -o json | jq '.items[] | select(.spec.containers[0].resources.requests.cpu | rtrimstr("m") | tonumber > 500) | .metadata.name'
# Nodes with taints
kubectl get nodes -o json | jq '.items[] | select(.spec.taints != null) | {name: .metadata.name, taints: .spec.taints}'
The Utility Cheat Sheet
| Need | Command |
| All Pod names | kubectl get pods -o name |
| Pod IPs | kubectl get pods -o wide |
| Specific field | -o jsonpath='{.field}' |
| Custom table | -o custom-columns=... |
| Process with jq | -o json | jq ... |
| Full YAML | -o yaml |
7. Label Selectors and Field Selectors
Label Selectors
Filter by labels:
bash
# Equality
kubectl get pods -l app=nginx
kubectl get pods -l app=nginx,env=prod
# Set-based
kubectl get pods -l 'env in (prod,staging)'
kubectl get pods -l 'env notin (dev)'
kubectl get pods -l 'app=nginx,env!=dev'
kubectl get pods -l '!canary'
# Exists
kubectl get pods -l 'app'
# Multiple with comma = AND
kubectl get pods -l 'app=nginx,version=1.25'
Field Selectors
Filter by object fields (limited to certain fields):
bash
# Pod phase
kubectl get pods --field-selector status.phase=Running
kubectl get pods --field-selector status.phase!=Running
# Node
kubectl get pods --field-selector spec.nodeName=node-1
# Multiple
kubectl get pods --field-selector status.phase=Running,spec.nodeName=node-1
Supported fields vary by resource. For Pods:
| Field | Purpose |
metadata.name | Pod name |
metadata.namespace | Namespace |
spec.nodeName | Node name |
status.phase | Pending/Running/Succeeded/Failed |
status.podIP | Pod IP |
Combining Both
bash
# Both label and field selector
kubectl get pods -l app=nginx --field-selector status.phase=Running
The Powerful Use Cases
bash
# Delete all Failed Pods
kubectl delete pods --field-selector status.phase=Failed
# Get all Pods on a specific node
kubectl get pods -A --field-selector spec.nodeName=node-1
# Get all Pods with a specific label
kubectl get pods -A -l app=nginx
# Get all containers in a label group
kubectl get pods -l app=nginx -o jsonpath='{.items[*].spec.containers[*].image}'
8. kubectl patch
kubectl patch modifies specific fields without replacing the whole resource.
Three Patch Types
| Type | Flag | Format |
| Strategic merge | default | YAML fragment |
| JSON merge | --type=merge | JSON fragment |
| JSON patch | --type=json | RFC 6902 operations |
Strategic Merge Patch
Merges YAML, using resource-specific merge logic:
bash
kubectl patch deployment web -p '{"spec":{"replicas":5}}'
kubectl patch deployment web -p '
spec:
template:
spec:
containers:
- name: web
image: nginx:1.26-alpine
'
The strategic part: Merges arrays by key (e.g., name in containers), not by index.
JSON Merge Patch
Merges JSON, no resource-specific logic:
bash
kubectl patch deployment web --type=merge -p '{"spec":{"replicas":5}}'
Arrays are replaced, not merged.
JSON Patch
Precise operations (add, remove, replace, move, copy, test):
bash
# Replace replicas
kubectl patch deployment web --type=json -p='[{"op":"replace","path":"/spec/replicas","value":5}]'
# Add annotation
kubectl patch deployment web --type=json -p='[{"op":"add","path":"/metadata/annotations/new-anno","value":"value"}]'
# Remove label
kubectl patch deployment web --type=json -p='[{"op":"remove","path":"/metadata/labels/old-label"}]'
# Test then replace
kubectl patch deployment web --type=json -p='[
{"op":"test","path":"/spec/replicas","value":3},
{"op":"replace","path":"/spec/replicas","value":5}
]'
When to Use Patches
| Scenario | Patch Type |
| Simple field change | Strategic merge |
| Array element update | Strategic merge |
| Add/remove specific field | JSON patch |
| Conditional update | JSON patch with test |
| Atomic multi-field change | JSON patch |
The kubectl patch Advantage
Patches are:
- Smaller than full manifests
- Safer (only touch specific fields)
- Faster than
edit(no editor) - Scriptable
Common Patterns
bash
# Scale
kubectl patch deployment web -p '{"spec":{"replicas":5}}'
# Add annotation
kubectl patch deployment web -p '{"metadata":{"annotations":{"owner":"alice"}}}'
# Add label
kubectl patch deployment web -p '{"metadata":{"labels":{"env":"prod"}}}'
# Update image
kubectl patch deployment web -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","image":"nginx:1.26-alpine"}]}}}}'
# Add resource limits
kubectl patch deployment web -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","resources":{"limits":{"memory":"512Mi"}}}]}}}}'
# Remove finalizer
kubectl patch pod stuck-pod --type=json -p='[{"op":"remove","path":"/metadata/finalizers"}]'
9. kubectl edit, scale, set, rollout
kubectl edit
Opens the live resource in your editor. Changes are validated and applied on save.
bash
kubectl edit deployment web
kubectl edit svc nginx
kubectl edit configmap app-config
Pros: Fast for one-off changes.
Cons: Not reproducible, no review, easy to make mistakes.
Production tip: Never use edit in production. Use apply from a versioned manifest.
kubectl scale
Change replicas:
bash
kubectl scale deployment web --replicas=5
kubectl scale deployment web --replicas=0 # Scale to zero
kubectl scale statefulset db --replicas=3
kubectl scale deployment --all --replicas=3
kubectl scale deployment -l app=web --replicas=5
kubectl set
Update specific fields:
bash
# Image
kubectl set image deployment/web web=nginx:1.26-alpine
kubectl set image deployment/web web=nginx:1.26-alpine sidecar=busybox:1.36
# Resources
kubectl set resources deployment/web --limits=cpu=500m,memory=512Mi
kubectl set resources deployment/web --requests=cpu=100m,memory=128Mi
# Env vars
kubectl set env deployment/web LOG_LEVEL=debug
kubectl set env deployment/web --from=configmap/app-config
# ServiceAccount
kubectl set serviceaccount deployment/web app-sa
# Selector (rarely used)
kubectl set selector svc/web app=web
kubectl rollout
Manage Deployments, DaemonSets, StatefulSets:
bash
# Status
kubectl rollout status deployment/web
# History
kubectl rollout history deployment/web
kubectl rollout history deployment/web --revision=2
# Undo (rollback)
kubectl rollout undo deployment/web # Previous
kubectl rollout undo deployment/web --to-revision=1 # Specific
# Pause/Resume
kubectl rollout pause deployment/web
kubectl rollout resume deployment/web
# Restart (rolling restart)
kubectl rollout restart deployment/web
kubectl rollout restart statefulset/db
kubectl rollout restart daemonset/fluentd
The restart trick: kubectl rollout restart is the standard way to trigger a rolling restart without changing the image. Useful for picking up ConfigMap changes.
10. Events and Their Role in Debugging
Events are cluster-level notifications of what's happening. They're the single most underrated debugging tool.
Viewing Events
bash
# Current namespace
kubectl get events
# Sorted by time
kubectl get events --sort-by=.metadata.creationTimestamp
# Specific resource
kubectl get events --field-selector involvedObject.name=nginx-abc123
# Watch
kubectl get events -w
# All namespaces
kubectl get events -A
# Recent only
kubectl get events --field-selector type=Warning
# Since a time
kubectl get events --since=1h
In kubectl describe
Events appear at the bottom of describe:
bash
kubectl describe pod nginx-abc123
text
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 5m default-scheduler Successfully assigned default/nginx to node-1
Normal Pulling 5m kubelet Pulling image "nginx:1.25"
Normal Pulled 4m kubelet Successfully pulled image
Normal Created 4m kubelet Created container nginx
Normal Started 4m kubelet Started container nginx
Common Event Reasons
| Reason | Meaning |
| Scheduled | Pod assigned to node |
| Pulling | Pulling image |
| Pulled | Image pulled successfully |
| Failed | Image pull failed |
| BackOff | Retry backoff |
| Created | Container created |
| Started | Container started |
| Killing | Container being killed |
| Unhealthy | Probe failed |
| FailedScheduling | Can't schedule |
| Evicted | Pod evicted (node pressure) |
| FailedMount | Volume mount failed |
| FailedAttachVolume | Volume attach failed |
Event Retention
Events are ephemeral. By default, they last 1 hour in etcd. This means:
- If you don't look soon, they're gone
- Long-running incidents need external logging
- Tools like
kubectl-event-exporterpersist events to a backend
The Debugging Flow
text
1. kubectl get pods → spot the problem
2. kubectl describe pod → read Events
3. kubectl logs pod → read app logs
4. kubectl get events -A → cluster-wide context
11. kubectl debug and Ephemeral Containers
The killer feature for production debugging.
The Problem kubectl debug Solves
Traditional debugging:
kubectl execrequires the container to have a shell- Distroless images have no shell
- Starting a new Pod to debug requires network access, volume mounts, etc.
kubectl debug modes
Mode 1: Ephemeral container in a running Pod
bash
kubectl debug -it nginx-abc123 --image=busybox --target=nginx
This adds an ephemeral container to the Pod, sharing its network/process namespace. You can then:
ps auxto see processesnetstatto see connections- Read files via the shared mount namespace
Mode 2: Copy a Pod with modifications
bash
kubectl debug nginx-abc123 --copy-to=debug-pod --image=busybox
Creates a new Pod with the same spec but a different image.
Mode 3: Debug a Node
bash
kubectl debug node/node-1 -it --image=busybox
Creates a Pod on the node with host namespaces. Useful for node-level debugging.
Mode 4: Debug with a custom profile
bash
kubectl debug nginx-abc123 --profile=netadmin --image=nicolaka/netshoot
Profiles: legacy, general, baseline, netadmin, restricted, sysadmin.
Ephemeral Containers
Ephemeral containers are specifically designed for debugging. They:
- Can be added to running Pods
- Share the Pod's network/process namespace
- Have their own filesystem
- Cannot be removed (only Pod deletion removes them)
- Do not count against Pod resource limits
Example:
yaml
ephemeralContainers:
- name: debugger
image: busybox
command: ['sh']
targetContainerName: nginx
stdin: true
tty: true
Common Debug Images
| Image | Purpose |
| busybox | Small, has basic tools |
| nicolaka/netshoot | Network debugging (tcpdump, dig, curl) |
| alpine | Slightly larger, has more tools |
| ubuntu | Full Linux environment |
| koolkits/kubernetes | Kubernetes-focused |
| koolkits/java | Java-focused |
The Debug Workflow
bash
# 1. Pod is broken
kubectl get pods
# nginx-abc123 1/2 CrashLoopBackOff
# 2. Try to exec (may fail with distroless)
kubectl exec -it nginx-abc123 -- sh
# error: exec: "sh": executable file not found
# 3. Use kubectl debug
kubectl debug -it nginx-abc123 --image=busybox --target=nginx
# 4. Now you can inspect the container's process namespace
ps aux
cat /proc/1/cmdline
ls /proc/1/root/ # Container's root filesystem!
# 5. Clean up
kubectl delete pod nginx-abc123 # Or remove just the ephemeral container (not supported directly)
Security Considerations
| Risk | Mitigation |
| Ephemeral container escape | RBAC restrict pods/ephemeralcontainers |
| Privileged debugging | Avoid --profile=sysadmin unless needed |
| Data exposure | Debug containers can read Pod filesystem |
| Persistence | Ephemeral containers can't be removed individually |
RBAC for ephemeral containers:
yaml
- apiGroups: [""]
resources: ["pods/ephemeralcontainers"]
verbs: ["update"]
12. kubectl exec, port-forward, cp
kubectl exec
We covered exec basics in Part 1. Advanced patterns:
bash
# Redirect stdin
echo "hello" | kubectl exec -i nginx-abc123 -- cat
# Redirect stdout to file
kubectl exec nginx-abc123 -- cat /var/log/nginx/access.log > access.log
# No TTY (for scripts)
kubectl exec nginx-abc123 -- env
# Distroless (no shell, but binary exists)
kubectl exec nginx-abc123 -- /usr/bin/nginx -v
# Multiple containers
kubectl exec -it nginx-abc123 -c sidecar -- sh
The exec limitation: You can only exec into a container that has the binary you want. Distroless containers have no shell.
kubectl port-forward
Forwards a local port to a Pod or Service:
bash
# Pod
kubectl port-forward pod/nginx-abc123 8080:80
# Service
kubectl port-forward svc/nginx 8080:80
# Deployment
kubectl port-forward deployment/nginx 8080:80
# Specific local IP
kubectl port-forward --address=0.0.0.0 pod/nginx-abc123 8080:80
# Random local port
kubectl port-forward pod/nginx-abc123 :80
# Multiple ports
kubectl port-forward pod/nginx-abc123 8080:80 8443:443
# In the background
kubectl port-forward pod/nginx-abc123 8080:80 &
Limitations:
- Single connection at a time (actually multiple, but sequential)
- Not for production — use Ingress or LoadBalancer
- Can be slow — especially for high-throughput
Use cases:
- Accessing a database for debugging
- Testing a Service without exposing it
- Local development against a cluster
kubectl cp
Copies files between local and Pods:
bash
# Pod to local
kubectl cp nginx-abc123:/var/log/nginx/access.log ./access.log
# Local to Pod
kubectl cp ./config.yaml nginx-abc123:/etc/config/
# With namespace
kubectl cp -n prod nginx-abc123:/app/data.tar.gz ./data.tar.gz
# Specific container
kubectl cp -c sidecar nginx-abc123:/logs/ ./logs/
# Directory
kubectl cp nginx-abc123:/app/ ./app-backup/
# Symlink handling
kubectl cp --no-preserve nginx-abc123:/app/ ./app-backup/
Requirements:
tarmust be in the container- Fails on distroless images
Alternatives for distroless:
kubectl execwithcatand pipekubectl debugwith an ephemeral container that hastar- Copy from the node's filesystem
13. kubectl top, api-resources, explain, auth
kubectl top
Live resource usage:
bash
# Pods
kubectl top pods
kubectl top pods -A
kubectl top pods --sort-by=cpu
kubectl top pods --sort-by=memory
kubectl top pods -l app=nginx
# Containers
kubectl top pods --containers
# Nodes
kubectl top nodes
kubectl top nodes --sort-by=cpu
Requires metrics-server to be installed in the cluster.
Common issue: "error: Metrics API not available" — install metrics-server.
kubectl api-resources
Lists all resource types the cluster supports:
bash
kubectl api-resources
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false
kubectl api-resources --verbs=list,get
kubectl api-resources | grep -i deployment
Output:
text
NAME SHORTNAMES APIVERSION NAMESPACED KIND
pods po v1 true Pod
deployments deploy apps/v1 true Deployment
nodes no v1 false Node
Use for: Discovering what a cluster supports.
kubectl api-versions
Lists API versions:
bash
kubectl api-versions
# apps/v1
# batch/v1
# networking.k8s.io/v1
# ...
kubectl explain
Built-in documentation:
bash
# Resource
kubectl explain pod
kubectl explain deployment
kubectl explain service
# Field
kubectl explain pod.spec
kubectl explain pod.spec.containers
kubectl explain pod.spec.containers.resources
kubectl explain pod.spec.containers.resources.limits
# Recursive (all nested fields)
kubectl explain deployment --recursive
# Specific version
kubectl explain deployment.spec --api-version=apps/v1
The value: Never leave the terminal. Faster than browser.
kubectl auth can-i
Checks permissions:
bash
# Can I do X?
kubectl auth can-i create pods
kubectl auth can-i delete deployments
kubectl auth can-i get secrets -n prod
# As another user/SA
kubectl auth can-i list pods --as=system:serviceaccount:default:my-sa
kubectl auth can-i list pods --as=alice
# All permissions
kubectl auth can-i --list
kubectl auth can-i --list -n prod
# All namespaces
kubectl auth can-i list pods --all-namespaces
The debugging value: When something fails with "forbidden," use can-i to confirm what's allowed.
kubectl cluster-info
bash
kubectl cluster-info
# Kubernetes control plane is running at https://k8s.example.com:6443
# CoreDNS is running at https://...
kubectl cluster-info dump
# Dumps all cluster state for debugging
kubectl get --raw
Direct API access:
bash
# Get a resource via API path
kubectl get --raw /api/v1/namespaces/default/pods
kubectl get --raw /healthz
kubectl get --raw /metrics
# Pretty print
kubectl get --raw /api/v1/namespaces/default/pods | jq
14. kubectl Plugins
kubectl supports plugins: any executable named kubectl-<plugin> on the PATH becomes a subcommand.
How Plugins Work
If /usr/local/bin/kubectl-foo exists and is executable, then:
bash
kubectl foo # Runs kubectl-foo
krew (The Plugin Manager)
krew is the standard plugin manager:
bash
# Install krew
(
set -x; cd "$(mktemp -d)" &&
OS="$(uname | tr '[:upper:]' '[:lower:]')" &&
ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/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"
# Search plugins
kubectl krew search
# Install
kubectl krew install ctx
kubectl krew install ns
kubectl krew install neat
kubectl krew install tree
kubectl krew install who-can
kubectl krew install outdated
kubectl krew install images
kubectl krew install resource-capacity
kubectl krew install tail
kubectl krew install view-secret
kubectl krew install cost
# List installed
kubectl krew list
# Upgrade
kubectl krew upgrade
# Uninstall
kubectl krew uninstall ctx
Essential Plugins
| Plugin | Purpose |
| kubectx (ctx) | Switch contexts fast |
| kubens (ns) | Switch namespaces fast |
| neat | Clean YAML output |
| tree | Resource hierarchy |
| who-can | Check permissions |
| outdated | Find outdated images |
| images | List images per workload |
| resource-capacity | Cluster capacity view |
| tail | Multi-Pod log tailing |
| view-secret | Decode Secrets |
| cost | Cost visibility |
| popeye | Cluster sanitizer |
| kubectl-ice | Per-Pod resource view |
| kubectl-kruise | Enhanced rolling updates |
| kubectl-node-shell | SSH into nodes via Pod |
Building a Plugin
A plugin is just a script:
bash
#!/usr/bin/env bash
# File: /usr/local/bin/kubectl-hello
echo "Hello from a kubectl plugin!"
echo "Args: $@"
bash
chmod +x /usr/local/bin/kubectl-hello
kubectl hello world
# Hello from a kubectl plugin!
# Args: world
Notable Third-Party Plugins (Not in krew)
| Tool | Purpose |
| k9s | Full-screen TUI for Kubernetes |
| kubectl-aliases | Shell aliases for common commands |
| kubie | Context-aware kubeconfig manager |
| kubespy | Live watch a resource type |
| stern | Multi-Pod log tailing (better than kubectl tail) |
| popeye | Cluster sanitizer |
| kubectl-neat | Clean up YAML output |
The kubectl Alias Cheat Sheet
Add to your ~/.bashrc or ~/.zshrc:
bash
alias k='kubectl'
alias kg='kubectl get'
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgd='kubectl get deployment'
alias kd='kubectl describe'
alias kdd='kubectl describe deployment'
alias kl='kubectl logs'
alias klf='kubectl logs -f'
alias ke='kubectl exec -it'
alias ka='kubectl apply -f'
alias kdel='kubectl delete'
alias kx='kubectx'
alias kn='kubens'
# Add completion
source <(kubectl completion bash)
complete -F __start_kubectl k
15. kubectl diff and Dry Runs
kubectl diff
Shows what would change if you applied a manifest:
bash
kubectl diff -f deployment.yaml
kubectl diff -f ./manifests/
kubectl diff -k ./kustomize/
Output: A unified diff (like git diff) of the changes.
Use case: Preview changes before applying. Essential for safe changes.
Dry Runs
Client-side dry run:
bash
kubectl apply -f deployment.yaml --dry-run=client
kubectl apply -f deployment.yaml --dry-run=client -o yaml
- Doesn't send to server
- Validates locally
- Useful for generating manifests from commands
Server-side dry run:
bash
kubectl apply -f deployment.yaml --dry-run=server
- Sends to server
- Full validation including admission webhooks
- Better for pre-apply validation
Use cases:
| Scenario | Dry Run Mode |
| Generate manifest from imperative | --dry-run=client -o yaml |
| Validate YAML syntax | --dry-run=client |
| Check admission webhooks | --dry-run=server |
| Preview changes | kubectl diff |
16. Common Failure Patterns
The 10 failure patterns you'll see most.
1. CrashLoopBackOff
Symptoms: Pod status shows CrashLoopBackOff, restart count is high.
Root causes:
- App crashes on startup
- Missing ConfigMap or Secret
- Bad command or arguments
- Missing dependencies
Debug:
bash
kubectl describe pod <pod> # Check Events
kubectl logs <pod> # Current logs
kubectl logs <pod> --previous # Previous instance logs
kubectl get pod <pod> -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}'
2. ImagePullBackOff / ErrImagePull
Symptoms: Pod status shows ImagePullBackOff.
Root causes:
- Wrong image name or tag
- Private registry without
imagePullSecrets - Registry unreachable
- Docker Hub rate limit
Debug:
bash
kubectl describe pod <pod> | grep -A5 Events
kubectl get secret <registry-secret> -o yaml
3. Pending
Symptoms: Pod stays in Pending phase.
Root causes:
- Insufficient resources on any node
- Node selector/affinity mismatch
- Taints without tolerations
- PVC not bound
- PodDisruptionBudget blocks eviction
Debug:
bash
kubectl describe pod <pod> # Check Events
kubectl get nodes # Resource availability
kubectl describe nodes | grep -A5 "Allocated resources"
kubectl get pvc # PVC status
4. OOMKilled
Symptoms: Exit code 137, restart, OOMKilled in container status.
Root causes:
- Memory limit too low
- Memory leak
- Traffic spike
Debug:
bash
kubectl describe pod <pod> | grep -i oom
kubectl top pod <pod>
kubectl get pod <pod> -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}'
5. Readiness Probe Failures
Symptoms: Pod status shows Running but 0/1 READY, so it's not in Service endpoints.
Root causes:
- Probe path wrong
- App slow to start
- Startup dependencies not ready
Debug:
bash
kubectl describe pod <pod> | grep -A3 "Readiness"
kubectl exec <pod> -- curl -v localhost:<port>/<path>
6. Service Has No Endpoints
Symptoms: kubectl get endpoints <svc> returns <none>.
Root causes:
- Service selector doesn't match Pod labels
- Pods not Ready
- Wrong port names
Debug:
bash
kubectl describe svc <svc>
kubectl get pods -l <selector-from-service>
kubectl get endpoints <svc>
7. CreateContainerConfigError
Symptoms: Container can't start, config error.
Root causes:
- Missing ConfigMap
- Missing Secret
- Missing key in ConfigMap/Secret
Debug:
bash
kubectl describe pod <pod> | grep -A5 Events
kubectl get configmap <name>
kubectl get secret <name>
8. FailedScheduling
Symptoms: Pod stays Pending, Events show FailedScheduling.
Root causes:
- No node has enough resources
- Taints/affinity prevent scheduling
- PVC unbound
Debug:
bash
kubectl describe pod <pod> | grep -A5 "FailedScheduling"
kubectl get nodes -o wide
kubectl describe node <node> | grep -A5 "Taints"
9. FailedMount
Symptoms: Pod stuck in ContainerCreating, Events show FailedMount.
Root causes:
- PVC not bound
- Volume attach failed
- Node can't reach storage
Debug:
bash
kubectl describe pod <pod> | grep -A10 "FailedMount"
kubectl get pvc
kubectl get pv
10. Node NotReady
Symptoms: Node status shows NotReady.
Root causes:
- kubelet down
- Disk pressure
- Network partition
- Certificate expired
Debug:
bash
kubectl describe node <node>
kubectl get events --field-selector involvedObject.name=<node>
# SSH to node, check kubelet
ssh <node>
systemctl status kubelet
journalctl -u kubelet -n 100
PART 3: PRODUCTION FAILURE MODES
17. Top 10 Debugging Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | Debugging in wrong context | "Why isn't this working?" | Current context ≠ intended cluster | kubectl config current-context |
| 2 | Debugging in wrong namespace | "Pod not found" | Wrong namespace | kubectl config view --minify |
| 3 | Events expired | No events to inspect | Events last 1 hour | Use event exporter |
| 4 | Logs gone | Can't find root cause | Container restarted, old logs gone | Use --previous or log aggregation |
| 5 | Distroless no-shell | Can't exec | Image has no shell | Use kubectl debug |
| 6 | Metrics API down | kubectl top fails | metrics-server not installed | Install metrics-server |
| 7 | Version skew | Command fails oddly | kubectl too old/new | Match kubectl version |
| 8 | RBAC denied | "forbidden" errors | Insufficient permissions | kubectl auth can-i |
| 9 | Wrong resource name | "not found" | Typo, wrong kind | kubectl get <resource> |
| 10 | Stale kubeconfig | Auth failures | Token expired, cert expired | Re-auth, refresh kubeconfig |
18. Kubernetes Debugging Runbook
"Something is Broken" — Step-by-Step
text
STEP 1: Verify context and namespace
$ kubectl config current-context
$ kubectl config view --minify | grep namespace
STEP 2: Get the high-level picture
$ kubectl get pods -A | grep -v Running
$ kubectl get events -A --sort-by=.metadata.creationTimestamp | tail -20
$ kubectl get nodes
$ kubectl cluster-info
STEP 3: Identify the broken resource
$ kubectl describe pod <pod>
# Read Events at the bottom
STEP 4: Get logs
$ kubectl logs <pod> --tail=100
$ kubectl logs <pod> --previous
$ kubectl logs -l <label> --tail=50
STEP 5: Check endpoints and service
$ kubectl get svc <svc>
$ kubectl get endpoints <svc>
$ kubectl describe svc <svc>
STEP 6: Check resource usage
$ kubectl top pod <pod>
$ kubectl top node
STEP 7: Check nodes
$ kubectl describe node <node>
$ kubectl get --raw /api/v1/nodes/<node>/proxy/stats/summary | jq
STEP 8: For deeper debugging
$ kubectl debug -it <pod> --image=busybox --target=<container>
STEP 9: Check permissions (if "forbidden")
$ kubectl auth can-i <verb> <resource> -n <namespace>
STEP 10: Check config
$ kubectl get configmap <name> -o yaml
$ kubectl get secret <name> -o yaml
STEP 11: Escalate if unresolved
Quick Diagnostic Table
| Symptom | First Command | Then |
| Pod not starting | kubectl describe pod | kubectl logs --previous |
| Service unreachable | kubectl get endpoints | kubectl describe svc |
| Node issues | kubectl describe node | SSH to node |
| Permission denied | kubectl auth can-i | Check RBAC |
| Slow performance | kubectl top | Check limits |
| "Not found" | kubectl config current-context | Verify namespace |
19. Blast Radius Analysis
When kubectl Fails
| Component | Impact | Severity |
| kubectl unavailable | Can't manage cluster | SEV-2 |
| kubeconfig lost | Can't authenticate | SEV-2 |
| API server down | kubectl unusable; Pods keep running | SEV-1 |
| RBAC revoked | Specific user blocked | SEV-2 |
| Wrong context | Actions in wrong cluster | SEV-1 (potential) |
Mitigation
| Strategy | Implementation |
| Backup kubeconfig | Secure storage |
| Multiple kubeconfigs | Per-cluster, per-role |
| kubectx/kubens | Avoid wrong-context mistakes |
| Shell prompt | Show current context |
| RBAC auditing | Regular kubectl auth can-i reports |
| Emergency access | Break-glass kubeconfig |
PART 4: CAPACITY PLANNING & COST MODELING
20. Fleet-Wide Debugging with kubectl
Multi-Namespace Queries
bash
# All Pods across namespaces
kubectl get pods -A
# All failing Pods
kubectl get pods -A --field-selector=status.phase=Failed
# All Pods not Running
kubectl get pods -A | grep -v "Running\|Completed"
# All Deployments not fully available
kubectl get deployments -A | awk '$3 != $4'
# All PVCs not Bound
kubectl get pvc -A | grep -v Bound
# All nodes with issues
kubectl get nodes | grep -v "Ready"
Capacity Audits
bash
# CPU/memory requests per namespace
kubectl get pods -A -o json | jq -r '.items[] | "\(.metadata.namespace)\t\(.spec.containers[].resources.requests.cpu // "0")\t\(.spec.containers[].resources.requests.memory // "0")"' | awk '{ns[$1]+=$2; ns_mem[$1]+=$3} END {for (n in ns) print n, ns[n], ns_mem[n]}'
# Nodes with allocated resources
kubectl describe nodes | grep -A5 "Allocated resources"
# Missing requests/limits
kubectl get pods -A -o json | jq '.items[] | select(.spec.containers[].resources.requests == null) | .metadata.name'
Image Audits
bash
# All images running in the cluster
kubectl get pods -A -o jsonpath='{range .items[*]}{.spec.containers[*].image}{"\n"}{end}' | sort -u
# Pods using :latest
kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"/"}{.metadata.name}{"\t"}{.spec.containers[*].image}{"\n"}{end}' | grep ':latest'
The kubectl Audit Script
bash
#!/bin/bash
# cluster-audit.sh
echo "=== Cluster Info ==="
kubectl cluster-info
echo -e "\n=== Node Status ==="
kubectl get nodes
echo -e "\n=== Namespaces ==="
kubectl get namespaces
echo -e "\n=== Failing Pods ==="
kubectl get pods -A | grep -v "Running\|Completed"
echo -e "\n=== Recent Events (Warnings) ==="
kubectl get events -A --field-selector type=Warning --sort-by=.metadata.creationTimestamp | tail -20
echo -e "\n=== Resource Usage ==="
kubectl top nodes
echo -e "\n=== PVCs not Bound ==="
kubectl get pvc -A | grep -v Bound
echo -e "\n=== Deployments Not Ready ==="
kubectl get deployments -A | awk 'NR>1 && $3 != $4'
echo -e "\n=== Certificate Status ==="
kubectl get certificates -A 2>/dev/null || echo "cert-manager not installed"
21. Cost Visibility via kubectl
Resource Requests
bash
# Total CPU requests by namespace
kubectl get pods -A -o json | jq -r '
.items[] |
.metadata.namespace as $ns |
.spec.containers[] |
.resources.requests.cpu // "0" |
"\($ns)\t\(.)"
' | awk '{a[$1] += $2} END {for (n in a) print n, a[n]}'
Idle Resources
bash
# Pods using less than 10% of their request
kubectl get pods -A -o json | jq -r '.items[] | "\(.metadata.namespace)/\(.metadata.name)"' > pods.txt
while read pod; do
kubectl top pod $(echo $pod | tr '/' ' ') 2>/dev/null
done < pods.txt
Zombie Workloads
bash
# Deployments with 0 replicas
kubectl get deployments -A | awk '$2 == "0/0"'
# Pods older than 30 days
kubectl get pods -A --sort-by=.metadata.creationTimestamp | awk 'NR>1'
# Unused PVCs (no mounted pod)
kubectl get pvc -A
22. SLA & Availability Design for Debugging Access
Access SLA Design
| Target | Approach |
| 99.9% | kubectl with basic kubeconfig |
| 99.99% | Multiple kubeconfigs, HA control plane |
| 99.999% | Break-glass access, emergency RBAC |
Break-Glass Access
When normal access fails, you need a way in:
| Method | Description |
| Admin kubeconfig | Stored securely offline |
| Cloud IAM role | AWS/GCP/Azure admin role |
| Emergency service account | Static token, secret-stored |
| Node SSH | Direct node access as backup |
PART 5: ARCHITECTURE & STRATEGY
23. Standardizing kubectl Across Teams
The Standard Tooling
| Tool | Purpose |
| kubectl | Core CLI |
| kubectx/kubens | Context/namespace switching |
| k9s | TUI |
| stern | Multi-Pod logs |
| krew | Plugin manager |
| kubectl-neat | Clean YAML output |
| yq | YAML processing |
The Standard Aliases
Distribute a common ~/.kube/aliases.sh:
bash
alias k='kubectl'
alias kg='kubectl get'
alias kgp='kubectl get pods'
alias kgpa='kubectl get pods -A'
alias kgs='kubectl get svc'
alias kgd='kubectl get deployment'
alias kd='kubectl describe'
alias kdp='kubectl describe pod'
alias kl='kubectl logs'
alias klf='kubectl logs -f'
alias ke='kubectl exec -it'
alias ka='kubectl apply -f'
alias kdel='kubectl delete'
alias kx='kubectx'
alias kn='kubens'
alias kdebug='kubectl debug -it'
The Standard Shell Prompt
Show current context and namespace in your prompt:
bash
# In ~/.bashrc
kube_ps1() {
local ctx=$(kubectl config current-context 2>/dev/null)
local ns=$(kubectl config view --minify --output 'jsonpath={..namespace}' 2>/dev/null)
echo "($ctx/${ns:-default})"
}
PS1='\u@\h $(kube_ps1) \$ '
Or use kube-ps1 (a popular tool).
Dangerous Command Prevention
Guardrails:
bash
# Warn on delete
alias kdelete='read -p "Delete? (y/n) " -n 1 -r; echo; [[ $REPLY =~ ^[Yy]$ ]] && kubectl delete'
# Prevent prod context without confirmation
kubectl() {
local ctx=$(command kubectl config current-context 2>/dev/null)
if [[ "$ctx" == *"prod"* ]]; then
read -p "You are in PROD. Continue? (yes/no) " ans
[[ "$ans" != "yes" ]] && return 1
fi
command kubectl "$@"
}
24. kubectl in CI/CD and GitOps
CI/CD Patterns
Read-only access: CI should have limited permissions.
yaml
# CI service account
apiVersion: v1
kind: ServiceAccount
metadata:
name: ci-readonly
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: ci-readonly
rules:
- apiGroups: [""]
resources: ["pods", "services", "endpoints"]
verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
resources: ["deployments", "statefulsets"]
verbs: ["get", "list", "watch"]
GitOps vs Imperative CI
| Aspect | Imperative CI | GitOps |
| Who applies? | CI pipeline | In-cluster controller |
| Source of truth | CI logs | Git |
| Drift detection | Manual | Automatic |
| Rollback | Rerun pipeline | Git revert |
| Best for | Legacy | Modern |
GitOps tools: Argo CD, Flux.
kubectl for GitOps Debugging
bash
# Check what Argo CD has synced
kubectl get applications -n argocd
# Check specific app
kubectl describe application myapp -n argocd
# Force sync
argocd app sync myapp
# Check Flux
kubectl get kustomizations -A
kubectl get gitrepositories -A
25. Compliance & Security for kubectl Access
RBAC Best Practices
| Practice | Why |
| Least privilege | Minimal permissions per role |
| No cluster-admin for humans | Use break-glass only |
| Namespace-scoped | Prefer Role over ClusterRole |
| Audit access | Log all API calls |
| Rotate credentials | Short-lived tokens |
Audit Logging
Kubernetes API server can log every request:
yaml
# /etc/kubernetes/audit-policy.yaml
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: RequestResponse
resources:
- group: ""
resources: ["secrets"]
- level: Metadata
resources:
- group: ""
resources: ["pods", "deployments"]
omitStages:
- RequestReceived
Emergency Access
Break-glass kubeconfig stored in a secure location:
- Vault
- Sealed envelope in physical safe
- Separate cloud account with MFA
Emergency process:
- Announce incident
- Retrieve break-glass credentials
- Fix the issue
- Rotate credentials
- Post-mortem
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
PART 7: INCIDENT MANAGEMENT
35. kubectl Incident Post-Mortem Template
text
INCIDENT: Production Outage - Wrong Context Used During Debugging
DATE: 2024-01-15
DURATION: 23 minutes
SEVERITY: SEV-1
IMPACT: A debug command accidentally ran against production instead of staging.
TIMELINE:
14:00 - Engineer debugging staging issue
14:05 - Ran kubectl delete pod --all -n staging
14:06 - Realized wrong context was active
14:07 - Verified prod pods deleted
14:08 - Initiated incident response
14:15 - Rolled forward: restarted all deleted Pods via Deployments
14:20 - All services restored
14:23 - Incident closed
ROOT CAUSE:
Engineer had two terminals open. One had prod context, the other had
staging. The destructive command ran against the wrong terminal.
LESSONS LEARNED:
1. Context visibility in shell prompt is critical.
2. Destructive commands need confirmation prompts.
3. kubectx/kubens should be standard.
ACTION ITEMS:
[ ] Enforce context in shell prompt across the org (Owner: Platform, Due: 2024-01-18)
[ ] Add confirmation prompts for destructive commands (Owner: Platform, Due: 2024-01-20)
[ ] Training on context management (Owner: Team Lead, Due: 2024-01-25)
36. On-Call Runbook: kubectl Debugging
text
SYMPTOM: Alert fired; need to debug via kubectl.
STEP 1: Verify context and namespace
$ kubectl config current-context
$ kubectl config view --minify | grep namespace
STEP 2: High-level health check
$ kubectl get nodes
$ kubectl get pods -A | grep -v "Running\|Completed"
$ kubectl get events -A --field-selector type=Warning | tail -20
STEP 3: Focus on the affected service
$ kubectl get pods -l app=<service> -o wide
$ kubectl describe pod <specific-pod>
$ kubectl logs <specific-pod> --tail=100
STEP 4: Check connectivity
$ kubectl get endpoints <service>
$ kubectl get svc <service> -o yaml
STEP 5: Check resources
$ kubectl top pods -l app=<service>
$ kubectl describe node <node>
STEP 6: If Pod is broken
$ kubectl logs <pod> --previous
$ kubectl get pod <pod> -o jsonpath='{.status.containerStatuses[0].lastState}'
STEP 7: If deeper debugging needed
$ kubectl debug -it <pod> --image=nicolaka/netshoot --target=<container>
STEP 8: Document and escalate
37. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | Cluster-wide outage | 5 min | On-call + Platform + Management |
| SEV-2 | Service outage / degraded | 15 min | On-call + Platform |
| SEV-3 | Single Pod issue | 1 hour | On-call |
| SEV-4 | Configuration issue | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
38. Junior-Level Questions
| Question | Expected Answer |
What's the difference between kubectl get and kubectl describe? | get = summary, describe = detailed + events |
| How do you see Pod logs? | kubectl logs <pod> |
| How do you switch namespaces? | kubectl config set-context --current --namespace=X or -n flag |
| What's a kubeconfig? | Config file with cluster/user/context info |
| How do you delete a Pod? | kubectl delete pod <name> |
39. Mid-Level Questions
| Question | Expected Answer |
| Difference between apply and create? | apply = 3-way merge, idempotent. create = one-shot. |
| How do you get a Pod's IP? | kubectl get pod X -o jsonpath='{.status.podIP}' |
| What's the difference between labels and annotations? | Labels are selectable, annotations aren't |
| How do you debug a distroless container? | kubectl debug with ephemeral container |
What's the difference between --dry-run=client and =server? | client = local; server = full validation including webhooks |
40. Senior-Level Questions
| Question | Expected Answer |
| How do you structure a debugging runbook? | Context check → high-level → drill down → specific |
| How do you safely debug in production? | Read-only first, ephemeral containers, break-glass RBAC |
| What's the difference between strategic merge and JSON patch? | Strategic merges by key; JSON patch is precise operations |
| How do you find which Pod is using all the CPU? | kubectl top pods --sort-by=cpu |
| How do you audit who deleted a resource? | Audit logs / event history |
41. Staff/Principal Questions
| Question | Expected Answer |
| Design a standardized kubectl workflow for 100 engineers. | Context in prompt, kubectx/kubens, aliases, RBAC, ephemeral debug |
| How do you prevent wrong-context accidents? | Prompt, confirmation prompts, separate kubeconfigs, network isolation |
| How do you debug at scale across 1000 nodes? | Event exporters, log aggregation, kubectl plugins, fleet-wide queries |
| How do you enforce least privilege for kubectl? | RBAC + audit + temporary elevation |
| How do you train engineers on kubectl? | Labs, runbooks, pair debugging, internal docs |
Summary Cheat Sheet
| Concept | Key Takeaway |
| kubectl | Client that talks to API server via REST |
| kubeconfig | Config file with clusters/users/contexts |
| Context | cluster + user + namespace |
| Imperative | kubectl run, create, set, scale |
| Declarative | kubectl apply |
| Apply 3-way merge | last-applied + new + live |
| Server-side apply | Better than client-side, used by GitOps |
| -o jsonpath | Extract specific fields |
| -o custom-columns | Custom table output |
| -o yaml | Full resource |
| kubectl describe | Human-readable + Events |
| Events | Cluster notifications, last ~1 hour |
| kubectl debug | Ephemeral containers for distroless |
| kubectl patch | Modify specific fields |
| kubectl diff | Preview changes |
| CrashLoopBackOff | App crashing → check logs --previous |
| ImagePullBackOff | Image problem → check Events |
| Pending | Scheduling problem → check describe Events |
| OOMKilled | Memory limit → increase or fix leak |
| No endpoints | Selector mismatch |
Stage 3: Control Plane Internals — The Comprehensive Guide
PART 1: CORE THEORY
1. The Control Plane
The control plane is the brain of Kubernetes. It makes all the decisions: what runs where, how many replicas, what happens when something fails. It consists of four components that work together.
The Four Components
text
┌─────────────────────────────────────────────────────────────┐
│ CONTROL PLANE COMPONENTS │
│ │
│ ┌───────────────┐ ┌───────────────┐ │
│ │ kube- │ │ etcd │ │
│ │ apiserver │◄───►│ (State DB) │ │
│ │ (REST API) │ │ Raft quorum │ │
│ └───────┬───────┘ └───────────────┘ │
│ │ │
│ │ │
│ ┌───────┴───────┐ ┌───────────────┐ │
│ │ kube- │ │ kube- │ │
│ │ scheduler │ │ controller- │ │
│ │ (Filter → │ │ manager │ │
│ │ Score → │ │ (Reconcile) │ │
│ │ Bind) │ │ │ │
│ └───────────────┘ └───────────────┘ │
└─────────────────────────────────────────────────────────────┘
Component Responsibilities
| Component | Role | Stateful? |
| kube-apiserver | REST API, the only component that talks to etcd | Stateless |
| etcd | Key-value store, the single source of truth | Stateful |
| kube-scheduler | Assigns Pods to Nodes | Stateless |
| kube-controller-manager | Runs reconciliation loops | Stateless |
The Key Insight
Only the API server talks to etcd. Everything else talks to the API server. This is the fundamental design pattern.
2. The API Server
kube-apiserver is the front door to Kubernetes. Every kubectl command, every controller action, every kubelet heartbeat goes through it.
The Request Flow (Step by Step)
When a request hits the API server:
text
Request → Authentication → Authorization → Admission → etcd
│ │ │
▼ ▼ ▼
Who are you? Are you allowed? Should we
modify it?
Step 1: Authentication (AuthN)
The API server verifies identity using:
- TLS client certificates
- Service account tokens (JWTs)
- OIDC tokens
- Webhook authenticators
- Cloud IAM (AWS IAM, GCP IAM)
Step 2: Authorization (AuthZ)
The API server checks permissions using:
- RBAC (most common)
- ABAC (legacy)
- Node authorization
- Webhook authorization
Kubernetes authorization takes place after authentication. Usually, a client making a request must be authenticated before its request can be allowed; however, Kubernetes also allows anonymous requests in some circumstances.
Step 3: Admission Control
Admission controllers intercept requests after authentication and authorization but before persistence to etcd.
Admission control proceeds in two phases:
- Mutating admission controllers run first. They can modify the object.
- Validating admission controllers run second. They can only allow or deny.
A mutating webhook can change the object before it's saved, while a validating admission webhook can only allow or deny it. This ordering matters because mutations always run first, so validation sees the final version of the object.
Step 4: Persistence
If the request passes all checks, the API server writes it to etcd.
API Server Aggregation
The aggregation layer allows Kubernetes to be extended with additional APIs beyond what the core Kubernetes APIs offer. It runs in-process with the kube-apiserver.
This is how metrics-server, custom metrics, and other extension APIs work.
3. etcd
etcd is a distributed, reliable key-value store that serves as the single source of truth for all cluster state. If etcd is lost, the cluster is lost.
Why etcd Matters
| Fact | Detail |
| All cluster state lives in etcd | Pods, Services, ConfigMaps, Secrets, RBAC, everything |
| etcd uses Raft consensus | Guarantees consistency across nodes |
| etcd must have quorum | Majority of nodes must agree |
| etcd is the performance bottleneck | Slow etcd = slow cluster |
Raft Consensus and Quorum
etcd uses the Raft consensus algorithm. The core requirement is quorum: a majority of nodes must agree for a transaction to be committed.
The quorum formula:
text
Quorum = floor(N/2) + 1
3 nodes: quorum = 2, tolerates 1 failure
5 nodes: quorum = 3, tolerates 2 failures
7 nodes: quorum = 4, tolerates 3 failures
Why odd numbers? Even numbers don't improve fault tolerance. A 4-node cluster needs 3 nodes to confirm, but a 5-node cluster also needs only 3 nodes — yet the 5-node cluster can tolerate 2 failures versus 1 for the 4-node cluster.
Production recommendation: Use 3 nodes for most clusters, 5 for large-scale or high-availability-critical clusters. Never exceed 7 nodes — the performance overhead outweighs the fault tolerance benefit.
etcd Performance Requirements
| Requirement | Recommendation |
| Disk | SSD or NVMe with low fsync latency |
| Disk latency | < 10ms for fsync |
| Network | Low latency between etcd nodes (< 10ms) |
| Memory | Default 8 GB limit; monitor for quota issues |
| CPU | 2-4 dedicated cores |
The disk I/O warning: etcd's Raft messages (including heartbeats) must be persisted to the WAL log using fdatasync. If the underlying disk is a mechanical HDD, fsync latency can exceed 10ms, causing heartbeats to be delayed and triggering false leader elections.
etcd Heartbeat and Election Tuning
| Parameter | Default | Recommended (Cross-AZ) |
| heartbeat-interval | 100ms | 200ms |
| election-timeout | 1000ms | 1500ms+ |
The formula: election-timeout ≥ 5 × heartbeat-interval + max_network_rtt.
4. The Scheduler
kube-scheduler watches for unscheduled Pods (spec.nodeName is empty) and assigns each to a feasible Node.
The Filter → Score → Bind Pipeline
For every Pending Pod, the scheduler runs:
text
All Nodes
│
▼
PHASE 1: FILTERING
Drop nodes that can't fit the Pod
(resources, affinity, taints, ports)
│
▼
Feasible Nodes
│
▼
PHASE 2: SCORING
Score each feasible node (0-100)
(load balancing, spreading, locality)
│
▼
Highest-scoring node
│
▼
PHASE 3: BINDING
Write spec.nodeName onto the Pod
(via API server)
The scheduler only chooses and writes the node name onto the Pod. It doesn't start the container. Starting the container is the job of the kubelet on the chosen node.
The Scheduler Framework (Plugin Engine)
The scheduler is a plugin engine with ten extension points. Plugins register at different stages of the scheduling cycle.
| Extension Point | Purpose |
| QueueSort | Order Pods in the scheduling queue |
| PreFilter | Pre-process Pod info |
| Filter | Eliminate unsuitable nodes |
| PostFilter | Handle unschedulable Pods (preemption) |
| PreScore | Pre-process scoring |
| Score | Rank feasible nodes |
| Reserve | Reserve resources |
| Permit | Allow/deny/wait |
| PreBind | Pre-binding setup |
| Bind | Finalize placement |
The Default Scoring Strategy
The scheduler's default scoring strategy is LeastAllocated — it spreads workloads rather than packing them. This is intentional: it prioritizes failure-domain resilience over density.
Bin packing is opt-in via MostAllocated or RequestedToCapacityRatio in NodeResourcesFit.
The Critical Misunderstanding
The scheduler operates on requests, not actual usage. A Pod requesting 2 CPUs but using 200m looks like a 2-CPU Pod to every scoring and consolidation decision.
This is why right-sizing requests is critical for cluster efficiency.
5. The Controller Manager
kube-controller-manager is a single binary that bundles dozens of reconciliation loops.
The Controller Pattern
A controller is a continuous loop that:
- Observes the current state
- Compares it to the desired state
- Acts to reconcile the difference
text
Desired State (from API server)
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Controller Loop │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Observe │───►│ Compare │───►│ Act │ │
│ │ Current │ │ Desired vs │ │ (create, │ │
│ │ State │ │ Current │ │ update, │ │
│ └─────────────┘ └─────────────┘ │ delete) │ │
│ ▲ └──────┬──────┘ │
│ └──────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
What Controllers Run in kube-controller-manager
| Controller | What It Reconciles |
| Deployment | ReplicaSets for Deployments |
| ReplicaSet | Pods for ReplicaSets |
| Node | Node lifecycle, evictions |
| Job | Pods for Jobs |
| CronJob | Jobs on schedule |
| ServiceAccount | SA tokens |
| EndpointSlice | Service endpoints |
| Namespace | Namespace lifecycle |
| PersistentVolume | PV/PVC binding |
Special Roles
The controller-manager also:
- Signs CSRs (
--cluster-signing-cert-file,--cluster-signing-key-file) - Signs ServiceAccount tokens (
--service-account-private-key-file) - Knows the pod network range (
--cluster-cidr)
PART 2: ADVANCED CONCEPTS
6. Admission Webhooks
Mutating vs Validating
| Aspect | Mutating | Validating |
| Purpose | Modify the object | Allow or deny |
| When | First phase | Second phase |
| Can modify? | ✅ Yes | ❌ No |
| Can deny? | ✅ Yes | ✅ Yes |
The Ordering
- Mutating webhooks run first.
- Validating admission policies run.
- Validating webhooks run last.
Critical: Mutations by mutating webhooks cause all previously called webhooks to be called again.
Failure Policy
| Policy | Behavior |
| Fail | Reject the request if the webhook is unreachable |
| Ignore | Allow the request if the webhook is unreachable |
The default is Fail (unless overridden).
The recovery pattern: If a webhook is blocking cluster recovery, temporarily patch to Ignore:
bash
kubectl patch validatingwebhookconfiguration my-webhook --type='json' \
-p='[{"op":"replace","path":"/webhooks/0/failurePolicy","value":"Ignore"}]'
⚠️ Warning: This disables enforcement. Use only during confirmed outages.
Webhook Timeout
Admission webhooks created using admissionregistration.k8s.io/v1 default to 30-second timeout.
The Four Extension Points
| Controller | Purpose |
| MutatingAdmissionWebhook | External mutating webhooks |
| MutatingAdmissionPolicy | Declarative in-API mutations |
| ValidatingAdmissionWebhook | External validating webhooks |
| ValidatingAdmissionPolicy | Declarative in-API validation |
ValidatingAdmissionPolicy provides a way to embed declarative validation code within the API without relying on external HTTP callouts.
7. API Priority and Fairness (APF)
APF controls API server behavior under overload. It's stable since Kubernetes v1.29.
The Problem APF Solves
The legacy controls (--max-requests-inflight, --max-mutating-requests-inflight) limit outstanding work but don't ensure important requests get through.
How APF Works
| Concept | Purpose |
| FlowSchema | Categorize incoming requests |
| PriorityLevelConfiguration | Assign priority levels |
| Queue | Buffer requests during bursts |
| Fair Queuing | Prevent starvation |
APF classifies and isolates requests in a fine-grained way. It introduces limited queuing so no requests are rejected during brief bursts. Requests are dispatched using fair queuing so a poorly-behaved controller doesn't starve others.
The Priority Levels
APF has built-in priority levels:
| Level | Purpose |
| system | Control plane components |
| workload-high | Critical workloads |
| workload-low | Standard workloads |
| global-default | Everything else |
| catch-all | Fallback |
Enabling/Disabling
APF is enabled by default. Disable with:
text
kube-apiserver --enable-priority-and-fairness=false
The Long-Running Exception
Some requests classified as "long-running" — such as remote command execution or log tailing — are not subject to APF. This is also true for --max-requests-inflight without APF.
8. The Aggregation Layer
The aggregation layer allows Kubernetes to be extended with additional APIs.
How It Works
The aggregation layer runs in-process with the kube-apiserver. When a request comes in for a registered API group, the main API server proxies it to the extension API server.
What Uses It
| Extension | API Group |
| metrics-server | metrics.k8s.io |
| Custom Metrics | custom.metrics.k8s.io |
| Service Catalog | servicecatalog.k8s.io |
| KubeVirt | kubevirt.io |
When to Use Aggregation vs CRDs
| Approach | Use When |
| CRDs | You need custom resources with standard API behavior |
| Aggregation | You need custom API semantics, subresources, or protocols |
9. Leader Election
In an HA control plane, multiple instances of scheduler and controller-manager run, but only one is active.
How It Works
| Step | Action |
| 1 | All instances try to acquire a Lease object in kube-system |
| 2 | The winner becomes leader and does the work |
| 3 | The leader periodically renews the lease |
| 4 | If the leader dies, another instance acquires the lease |
Both controller-manager and scheduler run three instances (one per control plane node). Leader election ensures only one does the work at a time.
Lease Parameters
| Parameter | Default | Meaning |
| leaseDuration | 15s | How long the lease is valid |
| renewDeadline | 10s | Leader must renew before this |
| retryPeriod | 2s | How often followers retry |
The Failover Delay
If a leader dies, the new leader takes over after leaseDuration expires. Default: ~15 seconds. During this window, no reconciliation happens.
Graceful Leader Transition (Kubernetes 1.36+)
Previously, losing leadership meant os.Exit() and restart. Kubernetes 1.36 introduced graceful leader transition: on losing leadership, the component transitions to follower state and tries to become leader again, avoiding resource waste.
10. Version Skew Policy
Kubernetes components have version compatibility rules. Violating them causes subtle failures.
Supported Versions
The Kubernetes project maintains release branches for the most recent three minor releases. Example: 1.37, 1.36, 1.35.
Version Skew Rules
| Component | Rule |
| kube-apiserver (HA) | Newest and oldest instances within one minor version |
| kubelet | Must not be newer than apiserver; up to 3 minor versions older (2 for < 1.25) |
| kube-proxy | Must not be newer than apiserver; up to 3 minor versions older |
| kubectl | Within one minor version of apiserver (older or newer) |
Examples
| Scenario | Supported? |
| apiserver 1.37, kubelet 1.37 | ✅ |
| apiserver 1.37, kubelet 1.36 | ✅ |
| apiserver 1.37, kubelet 1.34 | ✅ |
| apiserver 1.37, kubelet 1.33 | ❌ |
| apiserver 1.37, kubelet 1.38 | ❌ (newer) |
The HA Narrowing Effect
If apiserver instances are at 1.37 and 1.36, kubelet is supported at 1.36, 1.35, and 1.34. Version 1.37 is not supported because that would be newer than the 1.36 apiserver instance.
11. Certificate Rotation
Control plane certificates expire. If they expire, the cluster breaks.
The Certificates
| Certificate | Default Validity |
| kube-apiserver serving cert | 1 year |
| kube-apiserver client cert | 1 year |
| etcd serving cert | 1 year |
| etcd peer cert | 1 year |
| kubelet client cert | 1 year |
| kubelet serving cert | 1 year |
| CA certificate | 10 years |
Rotation Methods
| Method | Description |
| kubeadm | kubeadm certs renew all |
| kucero | Automatic daemonset-based rotation |
| Manual | Regenerate and replace certificates |
| Cloud-managed | Managed by provider (EKS, GKE, AKS) |
Kucero is a Kubernetes daemonset that performs automatic control plane certificate rotation.
The Rotation Procedure
- Plan a maintenance window (control plane will be briefly unavailable)
- Back up etcd and certificates
- Run rotation command
- Restart control plane components
- Verify cluster health
Warning: Certificate rotation may cause temporary unavailability when components restart. For production, perform during a maintenance window.
12. etcd Compaction and Defragmentation
Why etcd Grows
etcd's database file grows over time even when you're not adding objects. Compaction removes old revisions logically, but the bbolt backend does not shrink the file on disk. Without defragmentation, the file grows indefinitely.
The Two Operations
| Operation | What It Does |
| Compaction | Removes old revisions from the logical keyspace |
| Defragmentation | Reclaims disk space by removing gaps from deleted keys |
Automatic Compaction
The Kubernetes API server passes --etcd-compaction-interval to trigger compaction periodically.
Manual Defragmentation
After compaction, defragment each etcd member:
bash
# Check fragmentation
etcdctl endpoint status --write-out=table
# Defragment one member at a time
etcdctl defrag --endpoints=https://etcd-1:2379
# Verify
etcdctl endpoint status --write-out=table
Warning: Defragmentation blocks the etcd member for the duration. Do one member at a time, never all at once.
Monitoring etcd Size
bash
# Database size
etcdctl endpoint status --write-out=table
# Alarm if DB size > 2 GB (default quota is 2 GB)
etcdctl alarm list
13. The Controller Pattern
The Informer Architecture
Controllers don't poll the API server. They use informers:
text
API Server
│
│ Watch
▼
┌─────────────────────────────────────────────────────────────┐
│ Informer │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Reflector │───►│ DeltaFIFO │───►│ Indexer │ │
│ │ (Watch) │ │ (Queue) │ │ (Cache) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ Workqueue │ │
│ │ (Rate- │ │
│ │ limited) │ │
│ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
The Four Components
| Component | Purpose |
| Reflector | Watches API server for changes |
| DeltaFIFO | Queue of changes |
| Indexer | Local cache for fast reads |
| Workqueue | Rate-limited work queue for the controller |
Why This Design
- No polling: Watch is event-driven
- Local cache: Reads don't hit the API server
- Rate limiting: Prevents API server overload
- Deduplication: Multiple changes to the same object collapse into one work item
14. Cloud Controller Manager
cloud-controller-manager integrates Kubernetes with cloud providers.
What It Does
| Controller | Cloud Integration |
| Node | Adds cloud metadata to Nodes |
| Route | Configures cloud network routes |
| Service | Provisions cloud load balancers |
| Volume | Provisions cloud storage |
The Decoupling Principle
Before cloud-controller-manager, cloud-specific code lived in kube-controller-manager. This made Kubernetes less portable. Cloud-controller-manager decouples cloud logic from core Kubernetes.
PART 3: PRODUCTION FAILURE MODES
15. Top 10 Control Plane Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | etcd quorum lost | API server unresponsive | Lost majority of etcd nodes | Restore quorum from remaining nodes |
| 2 | etcd disk full | API server errors, etcd alarm | Database grew beyond quota | Defragment, increase quota |
| 3 | etcd slow disk | High API latency | HDD instead of SSD | Move to SSD/NVMe |
| 4 | Certificates expired | kubelet can't connect | No rotation | Rotate certificates |
| 5 | Webhook blocking | All API writes fail | Webhook failurePolicy=Fail, webhook down | Patch to Ignore temporarily |
| 6 | Leader election flapping | Controllers not reconciling | Network latency, clock skew | Fix network, NTP |
| 7 | API server overload | 429 errors, timeouts | Too many requests | Enable APF, increase replicas |
| 8 | etcd leader election storm | High etcd latency | Network latency > election-timeout | Tune heartbeat/election |
| 9 | Controller manager OOM | Controllers not running | Memory leak | Increase memory, investigate |
| 10 | Version skew violation | Subtle failures | Components on incompatible versions | Upgrade to supported versions |
16. Control Plane Debugging Runbook
"Control Plane is Broken" — Step-by-Step
text
STEP 1: Check API server health
$ curl -k https://localhost:6443/healthz
$ kubectl get --raw /healthz
STEP 2: Check etcd health
$ etcdctl endpoint health --cluster
$ etcdctl endpoint status --cluster --write-out=table
STEP 3: Check control plane pods (if static pods)
$ crictl ps | grep -E "apiserver|etcd|scheduler|controller"
$ crictl logs <container-id>
STEP 4: Check control plane systemd units (if not static pods)
$ systemctl status kube-apiserver
$ systemctl status etcd
$ systemctl status kube-scheduler
$ systemctl status kube-controller-manager
STEP 5: Check certificates
$ kubeadm certs check-expiration
$ openssl x509 -in /etc/kubernetes/pki/apiserver.crt -noout -dates
STEP 6: Check etcd disk
$ df -h /var/lib/etcd
$ iostat -x 1 5 /dev/sdX
STEP 7: Check leader election
$ kubectl get leases -n kube-system
$ kubectl describe lease kube-scheduler -n kube-system
STEP 8: Check webhooks
$ kubectl get validatingwebhookconfigurations
$ kubectl get mutatingwebhookconfigurations
STEP 9: Check version skew
$ kubectl version
$ kubelet --version
STEP 10: Escalate
17. Blast Radius Analysis
What Happens When Control Plane Fails?
| Component | Impact | Severity |
| etcd down | Cluster unrecoverable; all state lost | SEV-1 |
| API server down | Can't manage cluster; Pods keep running | SEV-1 |
| Scheduler down | New Pods stay Pending | SEV-2 |
| Controller manager down | No reconciliation | SEV-2 |
| One etcd node down | No impact (quorum maintained) | SEV-3 |
| Two etcd nodes down (3-node cluster) | Quorum lost, cluster broken | SEV-1 |
The "Running Pods Keep Running" Guarantee
Key insight: If the control plane goes down, already-running Pods keep running. Kubelet doesn't need the API server to keep containers alive. You just can't make changes.
Mitigation Strategies
| Strategy | Implementation |
| 3-node etcd | Tolerates 1 failure |
| 5-node etcd | Tolerates 2 failures |
| etcd backup | Regular snapshots |
| Certificate rotation | kubeadm or kucero |
| Webhook failurePolicy | Careful with Fail vs Ignore |
| APF | Protect against overload |
PART 4: CAPACITY PLANNING & COST MODELING
18. etcd Sizing and Performance
etcd Capacity Planning
| Cluster Size | etcd Nodes | CPU | Memory | Disk |
| < 100 nodes | 3 | 2 | 8 GB | 50 GB SSD |
| 100-500 nodes | 3 | 4 | 16 GB | 100 GB SSD |
| 500-1000 nodes | 5 | 8 | 32 GB | 200 GB NVMe |
| > 1000 nodes | 5 | 16 | 64 GB | 500 GB NVMe |
etcd Performance Metrics
| Metric | Target |
| fsync latency | < 10ms |
| WAL fsync duration | < 25ms (p99) |
| DB size | < 2 GB |
| Leader changes | 0 per hour (stable) |
| Request latency | < 50ms (p99) |
The Disk I/O Warning
Mechanical HDDs have fsync latency > 10ms. This causes:
- Heartbeat delays
- False leader elections
- API server timeouts
Always use SSD or NVMe for etcd.
19. Control Plane Capacity Planning
API Server Scaling
| Factor | Impact |
| Requests/second | More API server replicas |
| Webhooks | Each webhook adds latency |
| APF | Protects against overload |
| Load balancer | Required for HA |
API Server Resource Requirements
| Cluster Size | CPU per replica | Memory per replica |
| < 100 nodes | 2 | 4 GB |
| 100-500 nodes | 4 | 8 GB |
| 500-1000 nodes | 8 | 16 GB |
| > 1000 nodes | 16 | 32 GB |
Scheduler and Controller Manager
| Component | CPU | Memory |
| Scheduler | 2 | 2 GB |
| Controller Manager | 2 | 4 GB |
20. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Control Plane SLA Design
| Target | Architecture |
| 99.9% | Single control plane, etcd backups |
| 99.99% | 3-node HA control plane, 3-node etcd |
| 99.999% | 5-node HA control plane, 5-node etcd, multi-AZ |
The Failover Time
| Failure | Failover Time |
| API server pod | Instant (load balancer) |
| Scheduler leader | ~15s (lease expiry) |
| Controller manager leader | ~15s (lease expiry) |
| etcd leader | ~1-2s (Raft election) |
PART 5: ARCHITECTURE & STRATEGY
21. Control Plane HA Architecture
The Standard HA Setup
text
┌─────────────────────────────────────────────────────────────┐
│ LOAD BALANCER (VIP) │
│ │
│ ┌───────────────┼───────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Control │ │ Control │ │ Control │ │
│ │ Plane 1 │ │ Plane 2 │ │ Plane 3 │ │
│ │ │ │ │ │ │ │
│ │ apiserver │ │ apiserver │ │ apiserver │ │
│ │ scheduler │ │ scheduler │ │ scheduler │ │
│ │ controller │ │ controller │ │ controller │ │
│ │ etcd │ │ etcd │ │ etcd │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ etcd quorum = 2 of 3 (tolerates 1 failure) │
└─────────────────────────────────────────────────────────────┘
Key Design Principles
| Principle | Why |
| Odd number of control planes | Maintains quorum |
| Load balancer for API server | High availability |
| Separate etcd disks | I/O isolation |
| Cross-AZ deployment | Fault isolation |
| Consistent versions | Avoid skew |
22. Multi-Cluster Control Plane Strategy
| Strategy | Description | Best For |
| Single cluster | One control plane, many workers | Small teams |
| Multi-cluster | Separate control planes per environment | Production |
| Hub-and-spoke | Central control plane, remote workers | Edge |
| Cluster API | Declarative cluster management | Fleet management |
The Management Cluster Pattern
text
┌─────────────────────────────────────────────────────────────┐
│ Management Cluster │
│ (Cluster API, Argo CD, Monitoring) │
│ │
│ ┌───────────────┐ ┌───────────────┐ │
│ │ Workload │ │ Workload │ │
│ │ Cluster 1 │ │ Cluster 2 │ │
│ └───────────────┘ └───────────────┘ │
└─────────────────────────────────────────────────────────────┘
23. Compliance & Security
| Framework | Control Plane Requirement |
| PCI-DSS | Encryption at rest (etcd), audit logs, RBAC |
| HIPAA | Encryption, audit trails, access controls |
| SOC2 | Change management, monitoring |
| FedRAMP | FIPS 140-2, hardened control plane |
CIS Kubernetes Benchmark Key Items
- □ etcd encryption at rest enabled
- □ Audit logging configured
- □ RBAC enabled
- □ No anonymous auth
- □ Control plane certificates rotated
- □ etcd backups configured
PART 6: HANDS-ON LABS
Lab 1: Inspect etcd Data
Goal: Read and understand etcd contents.
bash
# Set etcdctl alias
alias etcdctl='ETCDCTL_API=3 etcdctl \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key'
# Health check
etcdctl endpoint health
etcdctl endpoint status --write-out=table
# List all keys (careful — this can be large)
etcdctl get / --prefix --keys-only | head -50
# Get a specific key
etcdctl get /registry/namespaces/default
# Get pods
etcdctl get /registry/pods/default --prefix --keys-only | head -20
# Check database size
etcdctl endpoint status --write-out=table
# Check alarms
etcdctl alarm list
Lab 2: Back Up and Restore etcd
Goal: Practice disaster recovery.
bash
# Backup
ETCDCTL_API=3 etcdctl snapshot save /tmp/etcd-backup.db \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key
# Verify backup
ETCDCTL_API=3 etcdctl snapshot status /tmp/etcd-backup.db --write-out=table
# Restore (in a test environment!)
# WARNING: This replaces etcd data
# 1. Stop API server
# 2. Restore
# 3. Restart API server
# Restore command (do NOT run in production without testing)
# ETCDCTL_API=3 etcdctl snapshot restore /tmp/etcd-backup.db \
# --data-dir=/var/lib/etcd-restored
Lab 3: Trace an API Request Through Admission
Goal: See admission in action.
bash
# Create a simple Pod
kubectl run test --image=nginx
# Check events for admission activity
kubectl get events --field-selector involvedObject.name=test
# Check which admission controllers are enabled
kubectl exec -n kube-system <apiserver-pod> -- \
kube-apiserver --help 2>&1 | grep admission
# Or check the static pod manifest
cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep admission
# Create a Pod that violates a policy
kubectl run privileged --image=nginx --overrides='
{
"spec": {
"containers": [{
"name": "privileged",
"image": "nginx",
"securityContext": {"privileged": true}
}]
}
}'
# Expected: Error from PodSecurity admission
# Cleanup
kubectl delete pod test 2>/dev/null
Lab 4: Write a Mutating Admission Webhook
Goal: Build a webhook that adds labels.
Prerequisites: A Kubernetes cluster with webhook access.
python
# webhook.py
from flask import Flask, request, jsonify
import base64
app = Flask(__name__)
@app.route('/mutate', methods=['POST'])
def mutate():
admission_review = request.get_json()
pod = admission_review['request']['object']
# Add a label
patch = [
{
'op': 'add',
'path': '/metadata/labels/managed-by',
'value': 'my-webhook'
}
]
# Encode patch
patch_bytes = json.dumps(patch).encode()
patch_b64 = base64.b64encode(patch_bytes).decode()
return jsonify({
'apiVersion': 'admission.k8s.io/v1',
'kind': 'AdmissionReview',
'response': {
'uid': admission_review['request']['uid'],
'allowed': True,
'patchType': 'JSONPatch',
'patch': patch_b64
}
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8443, ssl_context='adhoc')
yaml
# webhook-config.yaml
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
name: label-webhook
webhooks:
- name: label-webhook.example.com
clientConfig:
url: https://webhook-service.default.svc:8443/mutate
rules:
- operations: ["CREATE"]
apiGroups: [""]
apiVersions: ["v1"]
resources: ["pods"]
admissionReviewVersions: ["v1"]
sideEffects: None
failurePolicy: Fail
Lab 5: Write a Validating Admission Webhook
Goal: Build a webhook that blocks privileged Pods.
python
# validating-webhook.py
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/validate', methods=['POST'])
def validate():
admission_review = request.get_json()
pod = admission_review['request']['object']
# Check for privileged containers
for container in pod['spec'].get('containers', []):
if container.get('securityContext', {}).get('privileged', False):
return jsonify({
'apiVersion': 'admission.k8s.io/v1',
'kind': 'AdmissionReview',
'response': {
'uid': admission_review['request']['uid'],
'allowed': False,
'status': {
'message': 'Privileged containers are not allowed'
}
}
})
return jsonify({
'apiVersion': 'admission.k8s.io/v1',
'kind': 'AdmissionReview',
'response': {
'uid': admission_review['request']['uid'],
'allowed': True
}
})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8443, ssl_context='adhoc')
yaml
# validating-webhook-config.yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: privileged-blocker
webhooks:
- name: privileged-blocker.example.com
clientConfig:
url: https://webhook-service.default.svc:8443/validate
rules:
- operations: ["CREATE", "UPDATE"]
apiGroups: [""]
apiVersions: ["v1"]
resources: ["pods"]
admissionReviewVersions: ["v1"]
sideEffects: None
failurePolicy: Fail
Lab 6: Configure API Priority and Fairness
Goal: Create a custom FlowSchema.
yaml
# flow-schema.yaml
apiVersion: flowcontrol.apiserver.k8s.io/v1
kind: FlowSchema
metadata:
name: my-app-flow
spec:
priorityLevelConfiguration:
name: workload-high
matchingPrecedence: 1000
rules:
- resourceRules:
- resources: ["pods", "deployments"]
verbs: ["*"]
apiGroups: ["*"]
subjects:
- kind: ServiceAccount
serviceAccount:
name: my-app
namespace: production
---
apiVersion: flowcontrol.apiserver.k8s.io/v1
kind: PriorityLevelConfiguration
metadata:
name: workload-high
spec:
type: Limited
limited:
nominalConcurrencyShares: 50
limitResponse:
type: Queue
queuing:
queues: 16
queueLengthLimit: 50
handSize: 4
bash
kubectl apply -f flow-schema.yaml
# Check APF debug
kubectl get --raw /debug/api_priority_and_fairness/dump_priority_levels | jq
# Check queues
kubectl get --raw /debug/api_priority_and_fairness/dump_queues | jq
Lab 7: Simulate Control Plane Failure
Goal: Understand what happens when components fail.
bash
# Check current health
kubectl get nodes
kubectl get pods -A | head
# Simulate scheduler failure (if scheduler is a Deployment)
# For static pods, this is more complex
# Alternative: cordon all nodes
kubectl cordon --all
# Try to create a Pod
kubectl run stuck --image=nginx
kubectl get pod stuck
# Expected: Pending
# Uncordon
kubectl uncordon --all
kubectl delete pod stuck
# Simulate API server failure (in a test cluster)
# Stop the API server static pod
# sudo mv /etc/kubernetes/manifests/kube-apiserver.yaml /tmp/
# Wait 30 seconds
# kubectl get nodes
# Expected: Can't connect to server
# Restore
# sudo mv /tmp/kube-apiserver.yaml /etc/kubernetes/manifests/
Lab 8: Rotate Control Plane Certificates
Goal: Practice certificate rotation.
bash
# Check certificate expiry
kubeadm certs check-expiration
# Backup current certificates
sudo cp -r /etc/kubernetes/pki /etc/kubernetes/pki-backup
# Rotate all certificates
sudo kubeadm certs renew all
# Restart control plane components
sudo systemctl restart kubelet
# Verify
kubeadm certs check-expiration
# If something goes wrong, restore
# sudo rm -rf /etc/kubernetes/pki
# sudo cp -r /etc/kubernetes/pki-backup /etc/kubernetes/pki
# sudo systemctl restart kubelet
Lab 9: Set Up a 3-Node HA Control Plane
Goal: Build an HA control plane.
Prerequisites: 3 VMs.
bash
# On all nodes: install kubeadm, kubelet, kubectl
# On node 1 (first control plane)
sudo kubeadm init \
--control-plane-endpoint "k8s-api.example.com:6443" \
--upload-certs \
--pod-network-cidr=10.244.0.0/16
# Set up kubectl
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
# Save the join command for control planes
kubeadm token create --print-join-command
kubeadm init phase upload-certs --upload-certs
# On node 2 and node 3 (join as control planes)
sudo kubeadm join k8s-api.example.com:6443 \
--token <token> \
--discovery-token-ca-cert-hash sha256:<hash> \
--control-plane \
--certificate-key <cert-key>
# Verify HA
kubectl get nodes
kubectl get pods -n kube-system
# Should see 3 apiserver, 3 etcd, 3 scheduler, 3 controller-manager
# Check etcd cluster
kubectl exec -n kube-system etcd-node1 -- \
etcdctl member list --write-out=table
PART 7: INCIDENT MANAGEMENT
33. Control Plane Incident Post-Mortem Template
text
INCIDENT: etcd Quorum Lost - Cluster Unavailable
DATE: 2024-01-15
DURATION: 2 hours
SEVERITY: SEV-1
IMPACT: Entire cluster unmanageable. API server returned errors.
TIMELINE:
14:00 - Monitoring alert: etcd quorum lost
14:03 - On-call engineer acknowledged
14:05 - Found 2 of 3 etcd nodes down (disk failure)
14:08 - Confirmed only 1 etcd node remaining (no quorum)
14:15 - Attempted to restart failed etcd nodes
14:30 - etcd nodes failed to start (corrupted data)
14:45 - Decided to restore from backup
15:00 - Restored etcd from snapshot on all nodes
15:30 - etcd quorum restored
16:00 - Cluster fully operational
16:00 - Incident closed
ROOT CAUSE:
Two etcd nodes experienced simultaneous disk failures.
Their data was corrupted and they could not rejoin.
Only 1 of 3 nodes remained — quorum lost.
LESSONS LEARNED:
1. etcd nodes need redundant storage (RAID, multiple disks)
2. etcd backups must be tested regularly
3. 3 nodes is minimum; 5 nodes would have survived
ACTION ITEMS:
[ ] Move etcd to RAID 1 storage (Owner: Platform, Due: 2024-01-20)
[ ] Test etcd restore monthly (Owner: SRE, Due: 2024-01-25)
[ ] Evaluate 5-node etcd cluster (Owner: Architecture, Due: 2024-02-01)
34. On-Call Runbook: Control Plane Down
text
SYMPTOM: kubectl can't connect, API server errors.
STEP 1: Check API server health
$ curl -k https://localhost:6443/healthz
$ curl -k https://<load-balancer>:6443/healthz
STEP 2: Check etcd
$ etcdctl endpoint health --cluster
$ etcdctl endpoint status --cluster --write-out=table
$ systemctl status etcd
STEP 3: Check control plane processes
$ crictl ps | grep -E "apiserver|etcd|scheduler|controller"
$ journalctl -u kubelet -n 100
STEP 4: Check certificates
$ kubeadm certs check-expiration
$ openssl x509 -in /etc/kubernetes/pki/apiserver.crt -noout -dates
STEP 5: Check disk
$ df -h /var/lib/etcd
$ iostat -x 1 5
STEP 6: Check network
$ ping <other-control-plane>
$ ss -tlnp | grep 2379
STEP 7: If etcd is down
$ systemctl restart etcd
$ journalctl -u etcd -n 100
STEP 8: If quorum is lost
# Restore from backup (see Lab 2)
# Or, if enough data survives:
$ etcdctl member remove <failed-member>
$ etcdctl member add <new-member>
STEP 9: Escalate
35. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | etcd down / quorum lost / API server down | 5 min | On-call + Platform + Management |
| SEV-2 | Scheduler down / controller manager down | 15 min | On-call + Platform |
| SEV-3 | Single etcd node down (quorum intact) | 1 hour | On-call |
| SEV-4 | Certificate expiring soon | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
36. Junior-Level Questions
| Question | Expected Answer |
| What are the control plane components? | apiserver, etcd, scheduler, controller-manager |
| What does the API server do? | Front door, REST API, only component that talks to etcd |
| What does etcd store? | All cluster state |
| What does the scheduler do? | Assigns Pods to Nodes |
| What does the controller manager do? | Runs reconciliation loops |
37. Mid-Level Questions
| Question | Expected Answer |
| What is the request flow? | AuthN → AuthZ → Admission → etcd |
| What is quorum? | Majority of etcd nodes |
| Why odd number of etcd nodes? | Even numbers don't improve fault tolerance |
| What is a mutating webhook? | Modifies objects before validation |
| What is APF? | API Priority and Fairness — flow control |
38. Senior-Level Questions
| Question | Expected Answer |
| How do you recover from etcd quorum loss? | Restore from snapshot |
| What causes etcd leader election storms? | Network latency > election-timeout |
| How do you tune etcd? | heartbeat-interval, election-timeout, disk I/O |
| What is version skew? | Supported version differences between components |
| How do you rotate control plane certificates? | kubeadm certs renew all |
39. Staff/Principal Questions
| Question | Expected Answer |
| Design a 99.99% control plane. | 3-node HA, multi-AZ, etcd backups, certificate rotation |
| How do you migrate from single to HA control plane? | kubeadm join, rebalance etcd, test failover |
| How do you handle control plane disaster recovery? | etcd snapshots, documented restore, regular drills |
| How do you secure the control plane? | RBAC, audit logging, encryption at rest, certificate rotation |
| How do you scale the API server? | More replicas, APF, load balancer |
Summary Cheat Sheet
| Concept | Key Takeaway |
| API Server | Front door. Only component that talks to etcd. |
| etcd | Single source of truth. Raft consensus. Needs quorum. |
| Quorum | floor(N/2) + 1. 3 nodes = 1 failure. 5 nodes = 2 failures. |
| Odd numbers | Even doesn't improve fault tolerance. |
| Scheduler | Filter → Score → Bind. One Pod, one node. |
| Controller Manager | Reconciliation loops. Leader election in HA. |
| Admission | Mutating first, then Validating. |
| Webhook failurePolicy | Fail = reject if down. Ignore = allow if down. |
| APF | Priority and fairness for API server overload. |
| Leader Election | Lease object in kube-system. ~15s failover. |
| Version Skew | 3 minor versions for kubelet, 1 for apiserver. |
| Cert Rotation | kubeadm certs renew. |
| etcd Compaction | Removes old revisions. |
| etcd Defrag | Reclaims disk space. |
| Aggregation Layer | Extends API with custom servers. |
Stage 4: Workloads & Lifecycle Deep Dive — The Comprehensive Guide
PART 1: CORE THEORY
1. The Workload Hierarchy
Kubernetes provides multiple workload types, each designed for a specific kind of application. Choosing the wrong one is a common source of production pain.
The Full Workload Family
text
┌─────────────────────────────────────────────────────────────┐
│ WORKLOAD TYPES │
│ │
│ STATELESS STATEFUL │
│ ┌───────────────┐ ┌───────────────┐ │
│ │ Deployment │ │ StatefulSet │ │
│ │ (ReplicaSet) │ │ (Ordered, │ │
│ │ │ │ Stable ID) │ │
│ └───────────────┘ └───────────────┘ │
│ │
│ NODE-LEVEL BATCH │
│ ┌───────────────┐ ┌───────────────┐ │
│ │ DaemonSet │ │ Job │ │
│ │ (One per │ │ CronJob │ │
│ │ node) │ │ (Scheduled) │ │
│ └───────────────┘ └───────────────┘ │
│ │
│ RAW │
│ ┌───────────────┐ │
│ │ Pod │ (Rarely used directly) │
│ └───────────────┘ │
└─────────────────────────────────────────────────────────────┘
Decision Matrix
| Workload | Stateless? | Identity? | Storage? | Ordering? | Use Case |
| Deployment | ✅ | ❌ | Shared | ❌ | Web apps, APIs |
| StatefulSet | ❌ | ✅ | Per-Pod | ✅ | Databases, queues |
| DaemonSet | ✅ | N/A | Node-local | N/A | Agents, CNI |
| Job | ✅ | ❌ | Optional | ❌ | Batch, migrations |
| CronJob | ✅ | ❌ | Optional | ❌ | Scheduled tasks |
| Pod | ✅ | ❌ | Optional | ❌ | Debugging |
The Controller Pattern
All workloads follow the same pattern:
text
User creates resource
│
▼
Controller observes
│
▼
Controller creates child resources (Pods, ReplicaSets)
│
▼
Controller reconciles continuously
Each workload is a controller with specific logic:
- Deployments → manage ReplicaSets → manage Pods
- StatefulSets → manage Pods with identity
- DaemonSets → manage Pods per node
- Jobs → manage Pods until completion
2. Deployments
A Deployment is the standard workload for stateless applications. It manages ReplicaSets, which manage Pods.
The Deployment → ReplicaSet → Pod Hierarchy
text
Deployment (web)
│
└── ReplicaSet (web-abc123) ← Current version
├── Pod web-abc123-1
├── Pod web-abc123-2
└── Pod web-abc123-3
│
└── ReplicaSet (web-def456) ← Old version (scaled to 0)
└── (0 pods)
Why ReplicaSets? They enable rolling updates and rollbacks. Each version of your Deployment gets its own ReplicaSet.
Deployment Strategies
| Strategy | Behavior | Downtime | Use Case |
| RollingUpdate | Gradual replacement | ❌ None | Default, production |
| Recreate | Kill all, then create new | ⚠️ Yes | Dev, incompatible versions |
RollingUpdate Parameters
yaml
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # Extra pods during update
maxUnavailable: 0 # Pods that can be down
The math:
| maxSurge | maxUnavailable | Behavior |
| 1 | 0 | Surge by 1, never drop below desired |
| 25% | 25% | Balanced (default) |
| 0 | 1 | No extra pods, one unavailable |
| 1 | 1 | Fast but risky |
For zero-downtime: maxUnavailable: 0 and at least 2 replicas.
The Update Lifecycle
text
1. User applies new Deployment (new image)
2. Deployment creates NEW ReplicaSet
3. New ReplicaSet scales up (respecting maxSurge)
4. Old ReplicaSet scales down (respecting maxUnavailable)
5. Repeat until new RS has all replicas, old RS has 0
6. Old RS is retained for rollback
Rollback and History
bash
# View history
kubectl rollout history deployment/web
# Rollback to previous
kubectl rollout undo deployment/web
# Rollback to specific revision
kubectl rollout undo deployment/web --to-revision=2
# Pause/resume (for multi-step changes)
kubectl rollout pause deployment/web
kubectl set image deployment/web web=nginx:1.26
kubectl set resources deployment/web --limits=cpu=500m
kubectl rollout resume deployment/web
# Restart (rolling restart)
kubectl rollout restart deployment/web
# Status
kubectl rollout status deployment/web
Revision History Limit
yaml
spec:
revisionHistoryLimit: 10 # Keep last 10 ReplicaSets (default)
Production tip: Keep enough history for rollback. 10 is usually fine; 5 for resource-constrained clusters.
Progress Deadline
yaml
spec:
progressDeadlineSeconds: 600 # Fail if not progressing in 10 min
If the rollout doesn't progress within this time, the Deployment is marked as failed. The ReplicaSet isn't deleted, but kubectl rollout status will exit with error.
Common Deployment Anti-Patterns
| Anti-Pattern | Why It's Bad |
| maxUnavailable: 100% | All pods down during update |
| replicas: 1 | No HA; every update is downtime |
| No readiness probe | Traffic routed to not-ready pods |
| revisionHistoryLimit: 0 | Can't rollback |
| :latest image tag | Non-deterministic updates |
| No resource requests/limits | Unpredictable scheduling |
3. StatefulSets
A StatefulSet manages stateful applications that require:
- Stable network identity
- Stable storage per replica
- Ordered deployment and scaling
The Identity Guarantee
| Aspect | Deployment | StatefulSet |
| Pod name | web-abc123-xyz (random) | web-0, web-1, web-2 (ordered) |
| Hostname | Same as Pod name | Same as Pod name (stable) |
| DNS | Random | web-0.web.default.svc.cluster.local |
| Storage | Shared or none | Per-Pod PVC (persistent) |
| Startup order | Parallel | Sequential (0 → 1 → 2) |
| Termination order | Parallel | Reverse (2 → 1 → 0) |
The Headless Service Requirement
StatefulSets require a Headless Service (clusterIP: None) for stable DNS.
yaml
apiVersion: v1
kind: Service
metadata:
name: db-headless
spec:
clusterIP: None
selector:
app: db
ports:
- port: 5432
name: postgres
Each Pod gets its own DNS record:
db-0.db-headless.default.svc.cluster.localdb-1.db-headless.default.svc.cluster.localdb-2.db-headless.default.svc.cluster.local
StatefulSet Example
yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres-headless
replicas: 3
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:16-alpine
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: pg-secret
key: password
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
ports:
- containerPort: 5432
name: postgres
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: fast-ssd
resources:
requests:
storage: 100Gi
Each Pod gets its own PVC: data-postgres-0, data-postgres-1, data-postgres-2. These PVCs are NOT deleted when the StatefulSet is deleted (data preservation).
Update Strategies
| Strategy | Behavior | Downtime |
| RollingUpdate | Update Pods in reverse order | ❌ None (if HA) |
| OnDelete | Manual Pod deletion triggers update | Manual control |
| Partitioned | Update only Pods ≥ partition | Canary releases |
Partitioned rolling update is the StatefulSet equivalent of canary:
yaml
spec:
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 2 # Only update Pods with ordinal >= 2
This updates postgres-2 only, letting you validate before updating postgres-1 and postgres-0.
The Scaling Behavior
Scale up: Pods created in order 0, 1, 2 (each waits for the previous to be Ready).
Scale down: Pods deleted in reverse order 2, 1, 0.
When to Use StatefulSets
| Application | Why StatefulSet |
| PostgreSQL / MySQL | Needs stable storage per replica |
| MongoDB replica sets | Members need stable identities |
| Kafka / RabbitMQ | Brokers need stable IDs |
| Elasticsearch | Nodes need stable names |
| ZooKeeper / etcd | Consensus requires stable IDs |
| Cassandra | Ring topology needs ordering |
When NOT to Use StatefulSets
| Application | Use Instead |
| Stateless web app | Deployment |
| App with shared storage | Deployment + ReadWriteMany PVC |
| App without stable ID needs | Deployment |
The Operational Complexity
StatefulSets are harder to operate than Deployments:
| Challenge | Why |
| Ordered startup | Slow if 100 replicas |
| PVC management | PVCs persist after deletion |
| Data migration | No automatic data movement |
| Backup | Per-Pod backup needed |
| Debugging | Harder to reset (data persists) |
Rule of thumb: Use StatefulSet only if you need stable identity + per-Pod storage. Otherwise, use Deployment.
4. DaemonSets
A DaemonSet ensures a Pod runs on every node (or a subset). Used for node-level services.
How DaemonSets Work
text
Cluster with 5 nodes
│
▼
DaemonSet "fluentd" (replicas=5, implicit)
│
├── Pod on node-1
├── Pod on node-2
├── Pod on node-3
├── Pod on node-4
└── Pod on node-5
When a new node joins, a new Pod is automatically created. When a node leaves, its Pod is garbage collected.
Common DaemonSets
| DaemonSet | Purpose |
| kube-proxy | Networking |
| CNI plugin | Pod networking (Cilium, Calico) |
| CSI node plugin | Storage |
| Fluent Bit / Filebeat | Log collection |
| Prometheus Node Exporter | Node metrics |
| Datadog / New Relic agent | APM |
| Falco / Tetragon | Runtime security |
| NVIDIA device plugin | GPU scheduling |
DaemonSet Example
yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: node-exporter
namespace: monitoring
spec:
selector:
matchLabels:
app: node-exporter
template:
metadata:
labels:
app: node-exporter
spec:
hostNetwork: true
hostPID: true
tolerations:
- operator: Exists # Tolerate all taints
containers:
- name: node-exporter
image: prom/node-exporter:v1.7.0
args:
- "--path.procfs=/host/proc"
- "--path.sysfs=/host/sys"
- "--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)"
ports:
- containerPort: 9100
hostPort: 9100
name: metrics
resources:
limits:
cpu: 200m
memory: 200Mi
requests:
cpu: 100m
memory: 100Mi
volumeMounts:
- name: proc
mountPath: /host/proc
readOnly: true
- name: sys
mountPath: /host/sys
readOnly: true
volumes:
- name: proc
hostPath:
path: /proc
- name: sys
hostPath:
path: /sys
The Toleration Requirement
DaemonSet Pods on control plane nodes need a toleration for the control-plane taint:
yaml
tolerations:
- key: node-role.kubernetes.io/control-plane
operator: Exists
effect: NoSchedule
Most DaemonSets use operator: Exists (tolerate all taints) to run on all nodes.
Node Selection
yaml
spec:
template:
spec:
nodeSelector:
node-type: gpu # Only on GPU nodes
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values: [us-east-1a, us-east-1b]
Update Strategies
| Strategy | Behavior |
| RollingUpdate | Update pods one node at a time |
| OnDelete | Update only when Pod is deleted |
yaml
spec:
updateStrategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1 # Update 1 node at a time
maxSurge: 0 # No extra Pods (fixed per node)
Note: DaemonSets don't support maxSurge > 0 because there's exactly one Pod per node.
DaemonSet Use Cases
| Use Case | Example |
| Log collection | Fluent Bit on every node |
| Metrics collection | node-exporter on every node |
| Networking | Cilium agent on every node |
| Storage | CSI node plugin on every node |
| Security | Falco on every node |
| GPU | NVIDIA device plugin on GPU nodes |
5. Jobs and CronJobs
Jobs
A Job runs Pods to completion. Unlike Deployments (which run forever), Jobs finish.
Job Patterns
| Pattern | Description |
| Single | One Pod runs to completion |
| Parallel fixed | N Pods complete successfully |
| Work queue | N workers process a queue |
| Indexed | Each Pod gets a unique index |
Single Job
yaml
apiVersion: batch/v1
kind: Job
metadata:
name: db-migrate
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: migrate
image: myapp:1.0
command: ["python", "manage.py", "migrate"]
Parallel Fixed
yaml
spec:
completions: 10 # Total successful completions needed
parallelism: 3 # Max concurrent Pods
Behavior: 3 Pods run concurrently. As each completes, a new one starts until 10 have succeeded.
Work Queue
yaml
spec:
parallelism: 5 # 5 workers
completions: 5 # Each worker processes until queue empty
# No completions specified = runs until all workers exit
Indexed Jobs (K8s 1.24+)
yaml
spec:
completions: 10
parallelism: 3
completionMode: Indexed
template:
spec:
containers:
- name: worker
image: myapp:1.0
env:
- name: JOB_COMPLETION_INDEX
valueFrom:
fieldRef:
fieldPath: metadata.annotations['batch.kubernetes.io/job-completion-index']
command: ["process.sh", "$(JOB_COMPLETION_INDEX)"]
Each Pod gets a unique index from 0 to completions-1. Perfect for sharded batch jobs.
Job Parameters
| Parameter | Purpose | Default |
| completions | Total successes needed | 1 |
| parallelism | Max concurrent Pods | 1 |
| backoffLimit | Retries before failure | 6 |
| activeDeadlineSeconds | Timeout for whole Job | None |
| ttlSecondsAfterFinished | Auto-delete after N seconds | None |
| completionMode | NonIndexed or Indexed | NonIndexed |
CronJobs
A CronJob creates Jobs on a schedule.
yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: backup
spec:
schedule: "0 2 * * *" # 2 AM daily
timeZone: "America/New_York" # Optional (K8s 1.27+)
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
startingDeadlineSeconds: 300
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: backup
image: backup-tool:1.0
command: ["/backup.sh"]
Cron Schedule Format
text
┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-6, Sun=0)
│ │ │ │ │
* * * * *
| Schedule | Meaning |
0 * * * * | Every hour |
0 0 * * * | Every day at midnight |
0 2 * * * | Every day at 2 AM |
0 0 * * 0 | Every Sunday |
0 0 1 * * | First of month |
*/15 * * * * | Every 15 minutes |
Concurrency Policy
| Policy | Behavior |
| Allow | Multiple Jobs run concurrently |
| Forbid | Skip if previous Job still running |
| Replace | Kill previous, start new |
CronJob Best Practices
| Practice | Why |
| Set concurrencyPolicy | Prevent overlap |
| Set startingDeadlineSeconds | Don't run too late |
| Use activeDeadlineSeconds | Prevent runaway jobs |
| Set resource limits | Predictable scheduling |
| Set ttlSecondsAfterFinished | Auto-cleanup |
| Use timeZone | Correct scheduling |
| Idempotent jobs | Safe retries |
Time Zones (K8s 1.27+)
yaml
spec:
schedule: "0 2 * * *"
timeZone: "America/New_York" # Schedules in EST
Without timeZone, schedules are in UTC.
6. Pod Lifecycle
Pod Phases
| Phase | Meaning |
| Pending | Accepted, waiting for scheduling or image pull |
| Running | At least one container running |
| Succeeded | All containers exited successfully (exit 0) |
| Failed | At least one container failed (exit ≠ 0) |
| Unknown | Can't determine state (usually node issue) |
Container States
| State | Meaning |
| Waiting | Not started (pulling image, waiting for dependency) |
| Running | Executing |
| Terminated | Finished or crashed |
Common Waiting Reasons
| Reason | Cause |
| ContainerCreating | Runtime is setting up |
| CrashLoopBackOff | Container keeps crashing |
| ImagePullBackOff | Can't pull image |
| ErrImagePull | Image pull error |
| CreateContainerConfigError | Bad config (missing ConfigMap/Secret) |
| CreateContainerError | Runtime failed to create |
| RunContainerError | Container failed to start |
| PodInitializing | Init containers still running |
The Full Lifecycle
text
1. User creates Pod
│
▼
2. Scheduler assigns to Node (Pending → Scheduled)
│
▼
3. Kubelet pulls images
│
▼
4. Init containers run sequentially
│
▼
5. Main containers start
│
▼
6. Startup probes (if defined) run
│
▼
7. Liveness and Readiness probes start
│
▼
8. Pod becomes Ready (Running → Ready)
│
▼
9. Terminating (when deleted or evicted)
│
▼
10. PreStop hook runs (if defined)
│
▼
11. SIGTERM sent to containers
│
▼
12. terminationGracePeriodSeconds wait
│
▼
13. SIGKILL if still running
│
▼
14. Pod removed
Restart Policy
| Policy | Behavior |
| Always | Restart on any exit (default for Deployments) |
| OnFailure | Restart only on non-zero exit |
| Never | Never restart |
Restart Backoff
Kubernetes uses exponential backoff for restarts:
text
1st restart: 10s
2nd: 20s
3rd: 40s
4th: 80s
5th: 160s
6th: 300s (max)
The restart counter resets after 10 minutes of successful running.
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.
PART 3: PRODUCTION FAILURE MODES
17. Top 10 Workload Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | CrashLoopBackOff | Pod keeps restarting | App crashes | Check logs, fix app |
| 2 | ImagePullBackOff | Can't pull image | Bad tag, auth | Fix image or secrets |
| 3 | OOMKilled | Exit 137 | Memory limit exceeded | Increase limit, fix leak |
| 4 | Readiness probe fails | Pod never Ready | Probe or app issue | Fix probe or app |
| 5 | PDB blocking drain | Can't drain node | PDB too strict | Adjust PDB |
| 6 | StatefulSet stuck | Pods won't start in order | Pod 0 unhealthy | Fix Pod 0 |
| 7 | Job never completes | Job stuck running | Non-idempotent job, hook failure | Fix job logic |
| 8 | PreStop hangs | Pod takes forever to terminate | PreStop script bug | Fix preStop |
| 9 | Slow rollout | Update takes hours | maxUnavailable too low, probes too strict | Tune rollout |
| 10 | Native sidecar incompatibility | Pod fails to start | K8s < 1.29 | Upgrade K8s or use traditional sidecar |
18. Workload Debugging Runbook
"Workload is Broken" — Step-by-Step
text
STEP 1: Check the workload status
$ kubectl get deployment/<name>
$ kubectl get statefulset/<name>
$ kubectl get pods -l app=<name>
STEP 2: Check the Pod
$ kubectl describe pod <pod>
# Look at Status, Events, Container States
STEP 3: Check logs
$ kubectl logs <pod>
$ kubectl logs <pod> --previous # If crashed
$ kubectl logs <pod> -c <container> # Multi-container
STEP 4: Categorize the issue
Pending → Scheduling issue
- Check node resources
- Check taints/tolerations
- Check PVC status
- Check PDB
ImagePullBackOff → Image issue
- Check image name/tag
- Check imagePullSecrets
- Check registry connectivity
CrashLoopBackOff → App issue
- Check logs --previous
- Check exit code
- Check env vars, ConfigMaps, Secrets
Running but not Ready → Probe issue
- Check probe endpoint
- Check describe pod for probe failures
- Test probe manually
Terminating (stuck) → Termination issue
- Check preStop hook
- Check terminationGracePeriodSeconds
- Check app SIGTERM handling
STEP 5: Check resource limits
$ kubectl top pod <pod>
$ kubectl describe pod <pod> | grep -A5 Resources
STEP 6: Check PDB
$ kubectl get pdb
$ kubectl describe pdb <name>
STEP 7: Check StatefulSet-specific issues
$ kubectl get pvc -l app=<name>
$ kubectl get pv
STEP 8: Deep debugging
$ kubectl debug -it <pod> --image=busybox --target=<container>
STEP 9: Escalate
19. Blast Radius Analysis
What Happens When Workloads Fail?
| Component | Impact | Severity |
| All replicas crash | Service down | SEV-1 |
| One replica crash | Degraded capacity | SEV-2 |
| StatefulSet Pod 0 down | Cluster unavailable | SEV-1 |
| PDB blocks drain | Can't upgrade cluster | SEV-2 |
| Job fails | Batch incomplete | SEV-3 |
| CronJob fails | Missed schedule | SEV-3 |
| Probe misconfiguration | Traffic to bad pods | SEV-2 |
Mitigation Strategies
| Strategy | Implementation |
| Multiple replicas | 3+ for production |
| Pod anti-affinity | Spread across nodes/AZs |
| Readiness probes | No traffic to bad pods |
| PodDisruptionBudgets | Protect during disruptions |
| Graceful shutdown | No dropped requests |
| Resource limits | Predictable behavior |
PART 4: CAPACITY PLANNING & COST MODELING
20. Workload Sizing Fundamentals
The Sizing Formula
text
Total capacity = sum(replicas) × requests × overcommit_factor
Example:
- 10 apps
- 3 replicas each
- 500m CPU, 512Mi memory per Pod
- 2x CPU overcommit, 1.5x memory overcommit
CPU: 10 × 3 × 500m × 2 = 30 cores
Memory: 10 × 3 × 512Mi × 1.5 = 23 GiB
Right-Sizing
| Signal | Action |
| CPU throttling > 5% | Increase CPU limit |
| OOMKilled | Increase memory limit |
| Low utilization (< 20%) | Decrease requests |
| High utilization (> 80%) | Increase requests |
The VPA Recommendation Workflow
bash
# Install VPA
kubectl apply -f https://github.com/kubernetes/autoscaler/raw/master/vertical-pod-autoscaler/deploy/vpa-v1-crd-gen.yaml
# Create VPA in recommendation mode
kubectl apply -f - <<EOF
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: web-vpa
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: web
updatePolicy:
updateMode: "Off" # Only recommendations
EOF
# Check recommendations
kubectl describe vpa web-vpa
21. Disruption Budget and Availability Math
Availability During Drain
With N replicas and PDB minAvailable: M:
text
Max pods that can be down = N - M
Example: 5 replicas, minAvailable: 3
Max down = 2
Drain time = 2 × pod_shutdown_time
The Drain Time Formula
text
Drain time = (replicas - minAvailable) × (terminationGracePeriodSeconds + eviction overhead)
Example:
- 5 replicas
- minAvailable: 3
- terminationGracePeriodSeconds: 30
Drain time = 2 × 30s = 60s
Availability Target
text
Availability = 1 - (downtime during disruption / total time)
With PDB, downtime is bounded by:
(N - M) / N × disruption_duration
22. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Workload SLA Design
| Target | Architecture |
| 99.9% | 3 replicas, PDB minAvailable: 2 |
| 99.99% | 3 replicas across 3 AZs, PDB, anti-affinity |
| 99.999% | Multi-region, 5+ replicas, chaos-tested |
PART 5: ARCHITECTURE & STRATEGY
23. Workload Patterns by Application Type
| Application Type | Workload | Replicas | Storage | Notes |
| Stateless web | Deployment | 3+ | None | PDB, probes, HPA |
| API service | Deployment | 3+ | None | Same |
| Database | StatefulSet | 1-3 | RWO | Anti-affinity, backups |
| Message queue | StatefulSet | 3+ | RWO | Cluster ID, no scale-to-0 |
| Cache | StatefulSet | 3+ | RWO | Memory-optimized nodes |
| Batch job | Job | N/A | Optional | Resource limits, backoff |
| Cron task | CronJob | N/A | Optional | Idempotent, timeouts |
| Node agent | DaemonSet | N/A | Host mount | Tolerations, resources |
| Log collector | DaemonSet | N/A | Host mount | Same |
24. Migration Strategies
VM to Kubernetes Migration
| Phase | Action |
| 1. Assess | Inventory VMs, dependencies |
| 2. Containerize | Build images, extract config |
| 3. Deploy stateless | Start with stateless services |
| 4. Migrate stateful | Use StatefulSets, external DBs |
| 5. Optimize | Right-size, autoscale, tune |
| 6. Decommission | Retire VMs |
The 12-Factor App Fit
| Factor | Kubernetes Support |
| Codebase | Container images |
| Dependencies | Container isolation |
| Config | ConfigMaps, Secrets |
| Backing services | Services, ExternalName |
| Build/release/run | CI/CD + image tags |
| Processes | Stateless containers |
| Port binding | Service abstraction |
| Concurrency | Horizontal scaling |
| Disposability | Graceful shutdown |
| Dev/prod parity | Same images everywhere |
| Logs | stdout/stderr |
| Admin processes | Jobs, CronJobs |
25. Compliance & Security for Workloads
| Framework | Workload Requirement |
| PCI-DSS | Non-root, read-only rootfs, PSS restricted |
| HIPAA | Encryption, audit, access controls |
| SOC2 | Change management, monitoring |
| FedRAMP | FIPS 140-2, PSS restricted |
Workload security checklist:
- □ Non-root user
- □ Read-only root filesystem
- □ Drop all capabilities
- □ seccomp RuntimeDefault
- □ Resource limits
- □ No privileged
- □ Image from trusted registry
- □ Image scanned
- □ NetworkPolicy applied
- □ Service account with minimal RBAC
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
PART 7: INCIDENT MANAGEMENT
35. Workload Incident Post-Mortem Template
text
INCIDENT: Deployment Rollout Failed - All Pods CrashLooping
DATE: 2024-01-15
DURATION: 15 minutes
SEVERITY: SEV-1
IMPACT: 100% of web service down. All users unable to access.
TIMELINE:
14:00 - Deployment web:v2.0.0 rolled out
14:01 - Alert: Pods in CrashLoopBackOff
14:02 - On-call engineer acknowledged
14:03 - Identified missing ConfigMap "web-config-v2"
14:05 - Rolled back deployment
14:07 - Pods recovering
14:15 - Full service restored
ROOT CAUSE:
Deployment referenced a new ConfigMap "web-config-v2" that was
never created. All pods failed to start.
LESSONS LEARNED:
1. ConfigMaps should be in the same Helm chart as Deployment
2. Readiness gates should block bad rollouts
3. CI should validate references
ACTION ITEMS:
[ ] Add CI validation for resource references (Owner: Platform, Due: 2024-01-20)
[ ] Configure deployment gates (Owner: SRE, Due: 2024-01-22)
[ ] Test rollback procedure (Owner: Team, Due: 2024-01-25)
36. On-Call Runbook: Workload Failures
text
SYMPTOM: Workload not performing as expected.
STEP 1: Identify the workload
$ kubectl get deployments,statefulsets,daemonsets,jobs,cronjobs -A
STEP 2: Check Pod status
$ kubectl get pods -l app=<name>
$ kubectl describe deployment <name>
STEP 3: Check for failures
$ kubectl describe pod <pod>
# Look at Events
STEP 4: Categorize
CrashLoopBackOff → check logs, env vars, ConfigMaps
Pending → check nodes, resources, taints
OOMKilled → check limits, memory usage
NotReady → check readiness probe
Terminating forever → check preStop, SIGTERM handling
STEP 5: Apply fix
# Rollback if bad deploy
$ kubectl rollout undo deployment/<name>
# Fix config
$ kubectl edit configmap <name>
# Scale up if overwhelmed
$ kubectl scale deployment/<name> --replicas=N
STEP 6: Verify
$ kubectl rollout status deployment/<name>
$ kubectl get pods -l app=<name>
STEP 7: Document
37. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | All replicas down / service unavailable | 5 min | On-call + Platform + Management |
| SEV-2 | Degraded / partial outage | 15 min | On-call + Platform |
| SEV-3 | Single Pod issue | 1 hour | On-call |
| SEV-4 | Configuration warning | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
38. Junior-Level Questions
| Question | Expected Answer |
| Difference between Deployment and StatefulSet? | Identity: Deployment = random, StatefulSet = stable |
| What is a DaemonSet? | Runs one Pod per node |
| What is a Job? | Runs Pods to completion |
| What's the difference between liveness and readiness? | Liveness = restart, readiness = remove from service |
| What is a PDB? | Limits concurrent disruptions |
39. Mid-Level Questions
| Question | Expected Answer |
| RollingUpdate vs Recreate? | RollingUpdate = gradual, Recreate = kill all then create |
| What is maxSurge/maxUnavailable? | Extra and unavailable Pods during update |
| What are init containers? | Sequential setup before main containers |
| What is a native sidecar? | Init container with restartPolicy: Always |
| How do probes interact? | Startup disables others until success |
40. Senior-Level Questions
| Question | Expected Answer |
| Why not use liveness probes on external deps? | Cascading failures |
| How do you achieve zero-downtime deploys? | maxUnavailable:0, readiness, graceful shutdown, PDBs |
| How do PDBs work during node drains? | Block evictions that violate the budget |
| What is the termination sequence? | preStop → SIGTERM → grace → SIGKILL |
| How do you tune probes? | Based on app behavior, test in staging |
41. Staff/Principal Questions
| Question | Expected Answer |
| Design a workload architecture for a global service. | Multi-region, anti-affinity, PDB, probes, graceful shutdown |
| How do you migrate a legacy app to K8s? | Containerize, extract config, use StatefulSet for state, tune |
| How do you standardize workloads across 100 teams? | Templates, policies, admission controllers |
| How do you cost-optimize workloads? | VPA, right-sizing, spot, bin-packing |
| How do you handle disruptive upgrades? | PDBs, node-by-node, blue/green clusters |
Summary Cheat Sheet
| Concept | Key Takeaway |
| Deployment | Stateless, rolling updates, ReplicaSets |
| StatefulSet | Stable identity, per-Pod storage, ordered |
| DaemonSet | One Pod per node |
| Job | Runs to completion |
| CronJob | Scheduled Jobs |
| Pod Phases | Pending → Running → Succeeded/Failed |
| Container States | Waiting → Running → Terminated |
| Startup Probe | Slow start; disables other probes |
| Liveness Probe | Restart on failure |
| Readiness Probe | Remove from service on failure |
| Init Containers | Sequential setup |
| Native Sidecar | Init container with restartPolicy: Always |
| Ephemeral Container | Debug without restart |
| PostStart | Runs after container starts |
| PreStop | Runs before SIGTERM |
| Graceful Shutdown | preStop + SIGTERM + grace period |
| terminationGracePeriodSeconds | Wait before SIGKILL (default 30) |
| PDB | Limits voluntary disruptions |
| QoS | Guaranteed > Burstable > BestEffort |
| PriorityClass | Scheduling and preemption priority |
Stage 5: Scheduling Deep Dive — The Comprehensive Guide
PART 1: CORE THEORY
1. The Scheduler
The kube-scheduler is a control plane component that watches for newly created Pods with no assigned node, and selects the best node for them.
What the Scheduler Does (and Doesn't Do)
| Does | Doesn't Do |
| Watches for unscheduled Pods | Start containers |
| Filters nodes by constraints | Manage container lifecycle |
| Scores feasible nodes | Handle networking |
| Binds Pod to node | Run health checks |
| Triggers preemption | Pull images |
Critical distinction: The scheduler only writes the node name onto the Pod object. The kubelet on the chosen node does the actual work of starting containers.
What Makes a Pod Unscheduled
A Pod is scheduled when its spec.nodeName field is empty. Once the scheduler assigns it, spec.nodeName is set and the kubelet on that node takes over.
yaml
apiVersion: v1
kind: Pod
metadata:
name: web
spec:
# nodeName: "" (empty → scheduler will assign)
containers:
- name: app
image: nginx
The Scheduler's Sources of Truth
| Source | What It Provides |
| Pod spec | Resource requests, affinity, tolerations, priority |
| Node status | Available resources, taints, labels, conditions |
| PV/PVC state | Storage availability |
| Topology | Zones, regions, hostnames |
The Scheduler's Perspective on Resources
The scheduler operates on requests, not actual usage. A Pod requesting 2 CPUs but using 200m is treated as a 2-CPU Pod during scheduling.
This is why right-sizing requests is critical for cluster efficiency. Over-requesting wastes capacity; under-requesting risks eviction.
2. The Scheduling Pipeline
For every Pending Pod, the scheduler runs a two-phase pipeline, then binds.
The Full Flow
text
┌─────────────────────────────────────────────────────────────┐
│ SCHEDULING PIPELINE │
│ │
│ Pod in Scheduling Queue │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ PHASE 1: FILTERING │ │
│ │ All nodes │ │
│ │ │ │ │
│ │ ├── NodeResourcesFit (enough CPU/mem?) │ │
│ │ ├── NodeAffinity (node labels match?) │ │
│ │ ├── TaintToleration (taints tolerated?) │ │
│ │ ├── PodAffinity (pod co-location?) │ │
│ │ ├── PodAntiAffinity (pod spreading?) │ │
│ │ ├── NodeUnschedulable (cordoned?) │ │
│ │ ├── VolumeBinding (PV available?) │ │
│ │ ├── TopologySpread (zone distribution?) │ │
│ │ └── ... │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ Feasible Nodes │ │
│ └────────────────────┬────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ PHASE 2: SCORING │ │
│ │ Each feasible node gets a score (0-100) │ │
│ │ │ │ │
│ │ ├── NodeResourcesBalancedAllocation │ │
│ │ ├── NodeResourcesFit (LeastAllocated) │ │
│ │ ├── InterPodAffinity │ │
│ │ ├── ImageLocality (image already cached?) │ │
│ │ ├── TaintToleration │ │
│ │ ├── PodTopologySpread │ │
│ │ └── ... │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ Highest-scoring node │ │
│ └────────────────────┬────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ PHASE 3: BINDING │ │
│ │ Write spec.nodeName to Pod via API server │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ If no feasible nodes: │
│ ├── Try preemption (evict lower-priority pods) │
│ └── Or, leave Pod in Pending │
└─────────────────────────────────────────────────────────────┘
The Default Scoring Strategy
The scheduler's default scoring is LeastAllocated — it spreads workloads rather than packing them.
Why? Failure-domain resilience. If all workloads are on one node and that node dies, everything is lost.
Bin packing is opt-in via MostAllocated or RequestedToCapacityRatio.
The Scheduling Cycle vs Binding Cycle
| Cycle | What Happens | Can Fail? |
| Scheduling Cycle | Filter + Score for one Pod | Yes → retry or preempt |
| Binding Cycle | Write nodeName to Pod | Yes → retry |
The scheduling cycle is synchronous per Pod, but multiple Pods can be in different cycles concurrently.
The Scheduling Queue
Pods enter one of three queues:
| Queue | Purpose |
| ActiveQueue | Pods ready to be scheduled |
| BackoffQueue | Pods that failed scheduling (retry with backoff) |
| UnschedulableQueue | Pods that can't be scheduled (waiting for events) |
When cluster state changes (node added, Pod deleted, etc.), Pods move from Unschedulable to Active.
3. Node Selectors
Node Selectors are the simplest way to constrain Pod scheduling to specific nodes. They are hard, all-or-nothing requirements.
How Node Selectors Work
yaml
apiVersion: v1
kind: Pod
metadata:
name: gpu-pod
spec:
nodeSelector:
gpu: "true" # Pod must run on a node labeled gpu=true
accelerator: nvidia-a100
containers:
- name: ml-app
image: ml-app:1.0
Labeling Nodes
bash
# Add a label
kubectl label nodes node-1 gpu=true
kubectl label nodes node-2 accelerator=nvidia-a100
# View labels
kubectl get nodes --show-labels
kubectl describe node node-1 | grep -A5 Labels
# Remove a label
kubectl label nodes node-1 gpu-
Pros and Cons
| Pros | Cons |
| Very simple to write | No soft preferences |
| Fast evaluation | No OR logic |
| Easy to understand | Pod stays Pending if no match |
| — | No operators like In, NotIn |
When to Use Node Selectors
| Scenario | Node Selector OK? |
Simple env separation (env: prod) | ✅ Yes |
Simple hardware type (disktype: ssd) | ✅ Yes |
| Complex multi-condition | ❌ Use Node Affinity |
| Prefer but don't require | ❌ Use Node Affinity |
| Pod co-location | ❌ Use Pod Affinity |
The Node Selector Trap
If you set nodeSelector: {gpu: "true"} and no node has that label, the Pod stays Pending forever with no clear indication why. Always use kubectl describe pod to see Events.
4. Node Affinity and Anti-Affinity
Node Affinity is the advanced version of Node Selectors. It supports:
- Hard requirements (
requiredDuringSchedulingIgnoredDuringExecution) - Soft preferences (
preferredDuringSchedulingIgnoredDuringExecution) - Rich operators (
In,NotIn,Exists,DoesNotExist,Gt,Lt)
Required Node Affinity
yaml
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values:
- us-east-1a
- us-east-1b
- key: node-type
operator: In
values:
- gpu
Behavior: Pod stays Pending if no node matches.
Preferred Node Affinity
yaml
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: node-type
operator: In
values:
- gpu
- weight: 50
preference:
matchExpressions:
- key: disktype
operator: In
values:
- ssd
Behavior: Scheduler tries to honor preferences, but schedules elsewhere if needed. Weights range 1-100.
The Operators
| Operator | Meaning |
In | Label value is in the list |
NotIn | Label value is not in the list |
Exists | Label exists (any value) |
DoesNotExist | Label does not exist |
Gt | Label value > specified (numeric) |
Lt | Label value < specified (numeric) |
Multiple nodeSelectorTerms = OR
yaml
nodeSelectorTerms:
- matchExpressions:
- key: zone
operator: In
values: [us-east-1a] # OR
- matchExpressions:
- key: zone
operator: In
values: [us-east-1b] # OR
Multiple matchExpressions = AND
yaml
nodeSelectorTerms:
- matchExpressions:
- key: zone
operator: In
values: [us-east-1a] # AND
- key: gpu
operator: In
values: ["true"] # AND
Combining Required and Preferred
yaml
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: topology.kubernetes.io/region
operator: In
values: [us-east-1] # MUST be in region
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values: [us-east-1a] # PREFER this zone
The "IgnoredDuringExecution" Meaning
requiredDuringScheduling = enforced at scheduling time.
IgnoredDuringExecution = if node labels change after the Pod is scheduled, the Pod keeps running.
So: Existing Pods aren't evicted if node labels change.
Common Node Affinity Patterns
| Pattern | Purpose |
| Zone spreading | Required in specific zones |
| Hardware targeting | GPU, NVMe, FPGA |
| Environment isolation | Dev/staging/prod nodes |
| Cost optimization | Spot vs on-demand |
| Compliance | Data residency (EU-only nodes) |
5. Pod Affinity and Anti-Affinity
Pod Affinity and Pod Anti-Affinity control Pod placement relative to other Pods, based on their labels.
Pod Affinity (Co-location)
Bring Pods together on the same node/zone.
yaml
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: cache
topologyKey: kubernetes.io/hostname
Behavior: This Pod must be scheduled on a node that already has a Pod labeled app=cache.
Use case: Web server needs to be close to its cache (low latency).
Pod Anti-Affinity (Spreading)
Keep Pods apart.
yaml
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: web
topologyKey: kubernetes.io/hostname
Behavior: This Pod must NOT be scheduled on a node that already has a Pod labeled app=web.
Use case: Ensure web replicas are on different nodes (HA).
The topologyKey
The topologyKey is the node label that defines the "failure domain":
| topologyKey | Meaning |
kubernetes.io/hostname | Per node |
topology.kubernetes.io/zone | Per zone |
topology.kubernetes.io/region | Per region |
| Custom label | Custom domain |
Example: topologyKey: topology.kubernetes.io/zone for pod anti-affinity spreads replicas across zones.
Soft vs Hard
yaml
# HARD: Pod stays Pending if no node satisfies
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector: {...}
topologyKey: kubernetes.io/hostname
# SOFT: Try to satisfy, but schedule anyway
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector: {...}
topologyKey: kubernetes.io/hostname
The HA Pattern (Multi-AZ)
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: web
topologyKey: topology.kubernetes.io/zone # One per zone
containers:
- name: web
image: nginx
Result: 3 replicas spread across 3 zones.
The Low-Latency Pattern (Co-location)
yaml
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: cache
topologyKey: kubernetes.io/hostname # Same node as cache
Result: Always on the same node as the cache. Reduces network latency.
The Cost of Pod Affinity/Anti-Affinity
| Operation | Cost |
| Pod Affinity (required) | High — scheduler must scan all Pods on each candidate node |
| Pod Anti-Affinity (required) | High — scheduler must ensure no matching Pod exists |
| Preferred versions | Lower cost but less strong guarantee |
Performance tip: For large clusters, prefer topologyKey: topology.kubernetes.io/zone over hostname, as it requires fewer nodes to check.
Pod Affinity/Anti-Affinity Gotchas
| Gotcha | Impact |
| Required anti-affinity with replicas > nodes | Pods stay Pending forever |
| Required affinity with no matching Pods | Pod stays Pending forever |
| Anti-affinity in small clusters | Can't schedule multiple replicas |
| Affinity to self | Circular dependency |
Production rule: Use required only when you're certain it can always be satisfied. Prefer preferred for flexibility.
6. Taints and Tolerations
Taints let a node repel Pods. Tolerations let a Pod be scheduled on a tainted node.
The Gatekeeper Model
| Concept | Where Set | Meaning |
| Taint | On the Node | "Don't schedule Pods here unless they tolerate this" |
| Toleration | On the Pod | "I can be scheduled on nodes with this taint" |
Taint Effects
| Effect | Behavior |
| NoSchedule | New Pods without toleration won't schedule here |
| PreferNoSchedule | Scheduler tries to avoid, but may schedule |
| NoExecute | Evicts existing Pods without toleration; new Pods won't schedule |
Adding Taints
bash
# Add a taint
kubectl taint nodes node-1 dedicated=gpu:NoSchedule
# Add with PreferNoSchedule
kubectl taint nodes node-2 workload=monitoring:PreferNoSchedule
# View taints
kubectl describe node node-1 | grep Taints
# Remove a taint
kubectl taint nodes node-1 dedicated-
Toleration Structure
yaml
spec:
tolerations:
- key: "dedicated"
operator: "Equal"
value: "gpu"
effect: "NoSchedule"
Toleration Operators
| Operator | Behavior |
| Equal | Taint key AND value must match |
| Exists | Taint key must match (any value) |
Toleration Examples
Tolerate a specific taint:
yaml
tolerations:
- key: "dedicated"
operator: "Equal"
value: "gpu"
effect: "NoSchedule"
Tolerate any taint on a key:
yaml
tolerations:
- key: "dedicated"
operator: "Exists"
effect: "NoSchedule"
Tolerate all taints (for DaemonSets):
yaml
tolerations:
- operator: "Exists"
Tolerate a taint for a limited time (NoExecute):
yaml
tolerations:
- key: "node.kubernetes.io/unreachable"
operator: "Exists"
effect: "NoExecute"
tolerationSeconds: 300
Built-in Taints
| Taint | Purpose |
node.kubernetes.io/not-ready | Node not ready |
node.kubernetes.io/unreachable | Node unreachable |
node.kubernetes.io/memory-pressure | Memory pressure |
node.kubernetes.io/disk-pressure | Disk pressure |
node.kubernetes.io/pid-pressure | PID pressure |
node.kubernetes.io/network-unavailable | Network unavailable |
node.kubernetes.io/unschedulable | Node cordoned |
node-role.kubernetes.io/control-plane | Control plane node |
The Control Plane Taint
Control plane nodes are tainted:
text
node-role.kubernetes.io/control-plane:NoSchedule
To schedule a Pod on control plane nodes:
yaml
tolerations:
- key: "node-role.kubernetes.io/control-plane"
operator: "Exists"
effect: "NoSchedule"
Warning: Running workloads on control plane nodes is risky. Only do it for cluster-critical services.
The NoExecute Effect
NoExecute is the most aggressive:
- New Pods without toleration → not scheduled
- Existing Pods without toleration → evicted
When a node becomes unreachable, the node.kubernetes.io/unreachable taint is added with NoExecute. The default toleration (auto-added to all Pods) is 300 seconds:
yaml
tolerations:
- key: "node.kubernetes.io/not-ready"
operator: "Exists"
effect: "NoExecute"
tolerationSeconds: 300
- key: "node.kubernetes.io/unreachable"
operator: "Exists"
effect: "NoExecute"
tolerationSeconds: 300
After 300 seconds (5 minutes), Pods are evicted from the unreachable node.
The Dedicated Node Pattern
Use case: Reserve nodes for specific workloads.
bash
# Taint the node
kubectl taint nodes gpu-node-1 dedicated=gpu:NoSchedule
yaml
# GPU workload tolerates the taint + uses node affinity
spec:
tolerations:
- key: "dedicated"
operator: "Equal"
value: "gpu"
effect: "NoSchedule"
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: dedicated
operator: In
values: [gpu]
Why both taint AND affinity?
- The taint keeps other Pods off the GPU node.
- The affinity keeps the GPU Pod on the GPU node.
Without affinity, a GPU Pod could be scheduled on a non-GPU node (if it tolerates the GPU taint and another node has no taint).
Common Taint/Toleration Patterns
| Pattern | Purpose |
| Dedicated GPU nodes | Taint GPU nodes; only GPU workloads tolerate |
| Dedicated monitoring nodes | Taint monitoring; only monitoring tolerates |
| Spot node isolation | Taint spot nodes; only batch tolerates |
| Control plane isolation | Built-in taint on control plane |
| Node with issues | System taints (not-ready, disk-pressure) |
PART 2: ADVANCED CONCEPTS
7. Priority Classes and Preemption
PriorityClass
A PriorityClass is a cluster-scoped object that assigns an integer priority to a Pod. Higher numbers = higher priority.
yaml
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: high-priority
value: 1000000
globalDefault: false
description: "For production critical services"
Built-in System PriorityClasses
| Class | Value | Purpose |
system-node-critical | 2000001000 | Node-level components (kube-proxy, CNI) |
system-cluster-critical | 2000000000 | Cluster-level components (DNS, metrics-server) |
These have reserved values to prevent user-defined priorities from exceeding them.
Using PriorityClass
yaml
apiVersion: v1
kind: Pod
metadata:
name: critical-api
spec:
priorityClassName: high-priority
containers:
- name: api
image: myapi:1.0
How Priority Affects Scheduling
- Queue order: Higher-priority Pods are scheduled first.
- Preemption: If a high-priority Pod can't schedule, lower-priority Pods may be preempted.
Preemption
When a high-priority Pod is Pending:
- Scheduler looks for nodes where the Pod would fit if some lower-priority Pods were removed.
- Picks the node that minimizes disruption.
- Marks lower-priority Pods for eviction.
- Binds the high-priority Pod to the node.
Key insight: Preemption is disruptive. Only use it when you genuinely need priority differentiation.
Preemption and PDBs
PDBs are respected during preemption. If evicting a Pod would violate its PDB, preemption is skipped for that Pod.
Preemption Anti-Patterns
| Anti-Pattern | Impact |
| All Pods same priority | No preemption benefit |
| Everything high priority | Defeats the purpose; races |
| Priority without PDBs | Preemption kills critical Pods |
| Ignoring system priorities | User Pods can preempt control plane Pods (rare) |
Priority Classes Design
| Priority | Use Case |
| 2000001000 | system-node-critical (reserved) |
| 2000000000 | system-cluster-critical (reserved) |
| 1000000 | Production user-facing APIs |
| 100000 | Production backend services |
| 10000 | Batch jobs, pipelines |
| 1000 | Development workloads |
| 0 | Default (no priority) |
8. Topology Spread Constraints
Topology Spread Constraints control how Pods are distributed across failure domains (zones, nodes, regions).
Why Topology Spread
Before Topology Spread Constraints, distributing Pods across zones required complex Pod anti-affinity. Topology Spread is more declarative and flexible.
Basic Topology Spread
yaml
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: web
Parameters:
| Parameter | Meaning |
maxSkew | Maximum difference in Pod count between domains |
topologyKey | Node label defining the domain |
whenUnsatisfiable | DoNotSchedule or ScheduleAnyway |
labelSelector | Which Pods to count |
minDomains | Minimum number of domains required (K8s 1.28+) |
The maxSkew Concept
text
Zone A: 2 Pods
Zone B: 1 Pod
Zone C: 2 Pods
maxSkew = 1 → OK
maxSkew = 0 → Would require zones to be exactly equal
maxSkew: 1 is the standard for HA.
whenUnsatisfiable
| Value | Behavior |
DoNotSchedule | Hard requirement — Pod stays Pending if constraint can't be met |
ScheduleAnyway | Soft preference — try to satisfy, but schedule anyway |
Multi-Zone HA Example
yaml
spec:
replicas: 6
template:
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: web
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: web
Result: 6 replicas evenly spread across zones (hard), and preferred to spread across nodes within a zone (soft).
Combining Node Affinity + Topology Spread
yaml
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: web
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: topology.kubernetes.io/region
operator: In
values: [us-east-1]
Result: Pods spread evenly across zones within us-east-1.
The minDomains Parameter (K8s 1.28+)
yaml
topologySpreadConstraints:
- maxSkew: 1
minDomains: 3
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: web
Behavior: If fewer than minDomains domains are available, the Pod stays Pending. This prevents scheduling in degraded clusters with fewer zones.
Topology Spread vs Anti-Affinity
| Aspect | Topology Spread | Anti-Affinity |
| Declarative | ✅ Yes | ⚠️ Less so |
| Balance | ✅ Even distribution | ❌ Only "not together" |
| Complexity | Simple maxSkew | Complex selectors |
| Performance | Better | Can be slow |
| Best for | HA, balanced spread | Strict co-location/separation |
Recommendation: Use Topology Spread for HA. Use Pod Anti-Affinity only when you need strict "never together" semantics.
9. Pod Topology Spread vs Anti-Affinity
This is a common question. Here's the breakdown.
When to Use Pod Anti-Affinity
| Scenario | Use Anti-Affinity? |
| Strict 1-per-node | ✅ Required anti-affinity |
| Never co-locate two specific apps | ✅ Required anti-affinity |
| Balance across zones | ❌ Use Topology Spread |
| Soft preference to spread | ❌ Use Topology Spread (ScheduleAnyway) |
When to Use Topology Spread
| Scenario | Use Topology Spread? |
| Even distribution across zones | ✅ Yes |
| Even distribution across nodes | ✅ Yes |
| Tolerate some skew | ✅ Yes (maxSkew) |
| Strict "never together" | ❌ Use Anti-Affinity |
The "Best of Both" Pattern
yaml
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: web
This is functionally equivalent to required pod anti-affinity with topologyKey: kubernetes.io/hostname, but with better performance and clearer semantics.
10. The Scheduler Framework
The Scheduler Framework is the plugin architecture that powers the scheduler. It has ten extension points where plugins can hook in.
The Extension Points
| Extension Point | Purpose |
| QueueSort | Sort Pods in the scheduling queue |
| PreFilter | Pre-process Pod info; check if feasible nodes exist |
| Filter | Eliminate infeasible nodes |
| PostFilter | Handle unschedulable Pods (preemption) |
| PreScore | Pre-process scoring |
| Score | Score each feasible node (0-100) |
| NormalizeScore | Normalize scores across plugins |
| Reserve | Reserve resources on the chosen node |
| Permit | Allow/deny/wait before binding |
| PreBind | Pre-binding setup |
| Bind | Finalize the binding |
The Plugin Cycle
text
For each Pod:
QueueSort → PreFilter → Filter
│
├── Feasible nodes exist → Continue
│
└── No feasible nodes → PostFilter (preemption)
│
PreScore → Score → NormalizeScore
│
Reserve → Permit → PreBind → Bind
Built-in Plugins
| Plugin | Extension Points |
| NodeResourcesFit | Filter, Score |
| NodeAffinity | Filter, Score |
| PodTopologySpread | PreFilter, Filter, PreScore, Score |
| InterPodAffinity | PreFilter, Filter, PreScore, Score |
| TaintToleration | Filter, Score |
| ImageLocality | Score |
| DefaultPreemption | PostFilter |
| VolumeBinding | PreFilter, Filter, Reserve, PreBind |
Custom Plugins
You can write your own plugins in Go and register them. Common use cases:
| Use Case | Plugin Type |
| Custom scoring | Score |
| Hardware-aware placement | Filter, Score |
| Custom preemption | PostFilter |
| Multi-tenant fairness | QueueSort, Score |
The KubeSchedulerConfiguration
The scheduler is configured via a YAML file:
yaml
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: default-scheduler
plugins:
score:
enabled:
- name: MyCustomScorer
weight: 5
disabled:
- name: NodeResourcesBalancedAllocation
This config is passed to kube-scheduler via --config=/path/to/config.yaml.
11. Custom Schedulers
You can run multiple schedulers in the same cluster. Each Pod specifies which scheduler to use.
Why Multiple Schedulers
| Use Case | Custom Scheduler |
| Batch jobs | Gang scheduling, queue-based |
| ML training | GPU-aware, gang, topology |
| HPC | NUMA-aware, network topology |
| Specialized hardware | FPGA, TPU |
| Custom policies | Business rules |
Deploying a Custom Scheduler
- Build a binary using the Scheduler Framework.
- Deploy it as a Deployment or static Pod.
- Register it with the API server (via ServiceAccount, RBAC).
- Pods specify
schedulerName: my-scheduler.
Using a Custom Scheduler
yaml
apiVersion: v1
kind: Pod
metadata:
name: batch-job
spec:
schedulerName: my-batch-scheduler
containers:
- name: worker
image: batch-worker:1.0
Pods without schedulerName use default-scheduler.
Real-World Custom Schedulers
| Scheduler | Purpose |
| Volcano | Batch AI/ML, gang scheduling |
| Kueue | Job queueing and quotas |
| YuniKorn | Big data, batch |
| Scheduler Plugins | ML, GPU-aware |
We'll cover these in detail in Stage 13 (AI/ML Workload Orchestration).
12. Scheduler Profiles
Multiple schedulers can be deployed as profiles within a single binary. Each profile has its own plugin configuration.
Configuring Multiple Profiles
yaml
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: default-scheduler
plugins:
score:
disabled:
- name: NodeResourcesBalancedAllocation
- schedulerName: batch-scheduler
plugins:
score:
enabled:
- name: NodeResourcesFit
weight: 10
disabled:
- name: NodeResourcesBalancedAllocation
- name: ImageLocality
Using a Profile
Pods reference the profile by name:
yaml
spec:
schedulerName: batch-scheduler
This is more efficient than running separate scheduler binaries.
13. The Descheduler
The Descheduler is a tool that evicts Pods to rebalance the cluster, applying the scheduler's rules to existing Pods.
Why the Descheduler
The scheduler makes decisions at Pod creation time. Over time, the cluster can become unbalanced due to:
- Node additions/removals
- Pod evictions
- Priority changes
- Workload changes
The Descheduler continuously looks for Pods that violate scheduling policies and evicts them, letting the scheduler re-place them.
Common Descheduler Strategies
| Strategy | Purpose |
| RemoveDuplicates | No two replicas on the same node |
| LowNodeUtilization | Balance resource usage across nodes |
| HighNodeUtilization | Pack workloads (for scale-to-zero) |
| RemovePodsViolatingInterPodAntiAffinity | Enforce anti-affinity |
| RemovePodsViolatingNodeAffinity | Enforce node affinity |
| RemovePodsViolatingNodeTaints | Enforce taints |
| RemovePodsViolatingTopologySpreadConstraint | Enforce spread |
| RemovePodsHavingTooManyRestarts | Evict crashlooping Pods |
| PodLifeTime | Evict Pods older than N |
Deploying the Descheduler
yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: descheduler-policy
namespace: kube-system
data:
policy.yaml: |
apiVersion: descheduler/v1alpha1
kind: DeschedulerPolicy
strategies:
RemoveDuplicates:
enabled: true
LowNodeUtilization:
enabled: true
params:
thresholds:
cpu: 20
memory: 20
pods: 20
targetThresholds:
cpu: 50
memory: 50
pods: 50
RemovePodsViolatingTopologySpreadConstraint:
enabled: true
Run as a CronJob or Deployment:
yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: descheduler
namespace: kube-system
spec:
schedule: "*/15 * * * *"
jobTemplate:
spec:
template:
spec:
serviceAccountName: descheduler-sa
containers:
- name: descheduler
image: registry.k8s.io/descheduler/descheduler:latest
args:
- --policy-config-file=/policy/policy.yaml
- --v=3
volumeMounts:
- name: policy
mountPath: /policy
volumes:
- name: policy
configMap:
name: descheduler-policy
The Descheduler Dry Run
Always start in dry-run mode:
bash
--dry-run
Then transition to actual evictions.
The PDB Interaction
The Descheduler respects PDBs. Pods protected by PDBs are not evicted if it would violate the budget.
14. NUMA-Aware Scheduling
NUMA (Non-Uniform Memory Access) is a memory architecture where CPUs access local memory faster than remote memory. For latency-sensitive workloads, NUMA placement matters.
The NUMA Topology
text
NUMA Node 0 NUMA Node 1
┌─────────────────────┐ ┌─────────────────────┐
│ CPU 0-7 │ │ CPU 8-15 │
│ Memory: 32 GB │ │ Memory: 32 GB │
└──────────┬──────────┘ └──────────┬──────────┘
│ │
└────────────┬───────────────────┘
│
Interconnect
NUMA-Aware Scheduling Requires Two Components
| Component | Purpose |
| Topology Manager | Kubelet-level NUMA alignment |
| CPU Manager | Static CPU allocation |
Enabling Topology Manager
In /var/lib/kubelet/config.yaml:
yaml
topologyManagerPolicy: single-numa-node
cpuManagerPolicy: static
Restart kubelet.
The Topology Policies
| Policy | Behavior |
| none | No alignment |
| best-effort | Try to align; don't fail |
| restricted | Align if possible; fail if not |
| single-numa-node | All resources on one NUMA node |
Pod Configuration for NUMA-Awareness
yaml
spec:
containers:
- name: latency-sensitive
resources:
requests:
cpu: "4"
memory: "8Gi"
limits:
cpu: "4"
memory: "8Gi" # Guaranteed QoS required
Requirements:
- QoS must be Guaranteed (requests == limits)
- CPU requests must be integers
When to Use NUMA-Aware Scheduling
| Workload | NUMA-Aware? |
| Low-latency trading | ✅ Yes |
| 5G/telecom | ✅ Yes |
| High-perf databases | ✅ Yes |
| General web apps | ❌ No |
| Batch jobs | ❌ No |
15. GPU Scheduling (Preview)
GPU scheduling is covered in depth in Stage 12. Key facts:
- NVIDIA Device Plugin exposes GPUs to Kubernetes.
- GPUs are not compressible — one Pod gets one GPU unless MIG/time-slicing is used.
- Node affinity targets GPU nodes.
- Taints keep non-GPU workloads off GPU nodes.
- Dynamic Resource Allocation (DRA) is the future (K8s 1.26+).
16. Gang Scheduling (Preview)
Gang scheduling requires all Pods in a group to be scheduled together, or none.
Why it matters for AI/ML: Distributed training jobs need all workers running simultaneously. If only some workers are scheduled, the job deadlocks.
Tools:
- Volcano — gang scheduling plugin
- Kueue — job queueing
- YuniKorn — gang scheduling
Covered in depth in Stage 13.
17. Scheduling Gates and Delays
Scheduling Gates (K8s 1.27+)
Scheduling gates let external controllers hold Pods out of scheduling until ready.
yaml
spec:
schedulingGates:
- name: "my-controller/ready"
The Pod stays Pending until a controller removes the gate.
Use case: Complex initialization sequences, multi-controller coordination.
Scheduler Delay Hints
The scheduler caches node information. For very large clusters, this cache can become stale. Delay hints help with accuracy.
PodSchedulingReadiness Gate
A feature gate in K8s 1.26+ that enables scheduling gates for Pods.
PART 3: PRODUCTION FAILURE MODES
18. Top 10 Scheduling Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | Pod stays Pending | kubectl get pods shows Pending | No node matches constraints | Check describe Events |
| 2 | Anti-affinity deadlock | Pods stuck Pending | Required anti-affinity + replicas > nodes | Use preferred or add nodes |
| 3 | Resource fragmentation | Nodes show free resources but Pods Pending | Fragmentation (no node has enough of a single resource) | Bin-pack or add larger nodes |
| 4 | Taint not tolerated | Pods Pending | Missing toleration | Add toleration |
| 5 | PDB blocks drain | Node drain hangs | PDB too strict | Adjust PDB or add nodes |
| 6 | Scheduler overload | Slow scheduling | Too many Pods | Scale scheduler, reduce churn |
| 7 | Priority inversion | Low-priority Pods preempted | Wrong priority classes | Fix priorities |
| 8 | Topology spread deadlock | Pods Pending | maxSkew too strict | Relax maxSkew |
| 9 | Volume binding delay | Pods stuck Pending | PV in different zone | Use WaitForFirstConsumer |
| 10 | Scheduler cache inconsistency | Pods scheduled on full nodes | Stale cache | Restart scheduler |
19. Scheduling Debugging Runbook
"Pod is Pending" — Step-by-Step
text
STEP 1: Confirm Pending
$ kubectl get pod <pod>
# STATUS = Pending
STEP 2: Describe the Pod (this is the source of truth)
$ kubectl describe pod <pod>
# Read Events section
STEP 3: Look for FailedScheduling events
# Events show exactly why scheduling failed
STEP 4: Categorize the issue
"Insufficient cpu/memory" → Resource issue
- Check node resources
- $ kubectl describe nodes | grep -A5 "Allocated resources"
"node(s) had taint" → Taint issue
- Check node taints
- $ kubectl describe node <node> | grep Taints
- Add toleration
"node(s) didn't match node selector" → Node selector/affinity issue
- Check node labels
- $ kubectl get nodes --show-labels
- Verify nodeSelector/affinity matches
"node(s) didn't match pod affinity" → Pod affinity issue
- Check if matching Pods exist
- $ kubectl get pods -l <selector>
"node(s) didn't match pod anti-affinity" → Anti-affinity issue
- Too strict for cluster size
- Relax to preferred
"node(s) exceed max volume count" → Volume limit
- Check node's volume limit
- Consider larger instance type
"waiting for ephemeral volume" → Volume binding issue
- Check PVC
- $ kubectl get pvc
STEP 5: Check nodes
$ kubectl get nodes
# Any NotReady? Any cordoned?
$ kubectl describe nodes | grep -A5 "Allocated resources"
STEP 6: Check priority classes
$ kubectl get pod <pod> -o jsonpath='{.spec.priorityClassName}'
$ kubectl get priorityclasses
STEP 7: Check PDBs
$ kubectl get pdb -A
$ kubectl describe pdb <name>
STEP 8: Try removing constraints (test)
# Remove nodeSelector temporarily to isolate
STEP 9: Escalate
Common Error Messages → Meaning
| Error Message | Meaning | Fix |
0/10 nodes are available: 5 Insufficient cpu | Resource shortage | Add nodes or reduce requests |
node(s) had taint {key: value}, that the pod didn't tolerate | Taint not tolerated | Add toleration |
node(s) didn't match Pod's node affinity | Affinity mismatch | Check labels |
node(s) didn't match pod anti-affinity rules | Anti-affinity conflict | Relax or add nodes |
node(s) had volume node affinity conflict | PV in wrong zone | Use WaitForFirstConsumer |
pod has unbound immediate PersistentVolumeClaims | PVC not bound | Check PVC/StorageClass |
0/10 nodes are available: 10 node(s) were unschedulable | All nodes cordoned | Uncordon |
20. Blast Radius Analysis
What Happens When Scheduling Fails?
| Component | Impact | Severity |
| All new Pods Pending | Service can't scale | SEV-1 |
| Single Pod Pending | Degraded capacity | SEV-2 |
| Scheduler down | All new Pods Pending | SEV-1 |
| Node drain blocked by PDB | Upgrade stuck | SEV-2 |
| Wrong priority | Preemption outages | SEV-2 |
| Fragmentation | Wasted capacity | SEV-3 |
Mitigation Strategies
| Strategy | Implementation |
| Multiple scheduler replicas | HA scheduling |
| Topology Spread (not Anti-Affinity) | Better performance |
| Preferred over Required | Flexibility |
| PDB design | Ensure drainability |
| PriorityClasses | Clear priorities |
| Descheduler | Rebalance |
PART 4: CAPACITY PLANNING & COST MODELING
21. Bin-Packing vs Spreading
Spreading (Default)
The default scheduler spreads workloads (LeastAllocated).
| Pros | Cons |
| Resilient to node failure | Lower utilization |
| Even distribution | More nodes needed |
| Simpler reasoning | Higher cost |
Bin-Packing
Bin-packing packs workloads (MostAllocated).
yaml
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: default-scheduler
pluginConfig:
- name: NodeResourcesFit
args:
scoringStrategy:
type: MostAllocated
resources:
- name: cpu
weight: 1
- name: memory
weight: 1
| Pros | Cons |
| Higher utilization | Less resilient |
| Lower cost | Risk of cascading failure |
| Fewer nodes | Noisy neighbors |
When to Use Which
| Scenario | Strategy |
| Production APIs | Spreading |
| Batch jobs | Bin-packing |
| Cost-sensitive | Bin-packing |
| Resilience-critical | Spreading |
| Mixed | Different profiles |
The Cost Impact
text
Spreading: 100 nodes at 40% utilization
Bin-packing: 60 nodes at 70% utilization
Cost savings: 40% fewer nodes
Risk: One node failure affects 70% of workloads
22. Cost-Aware Scheduling
Spot Instance Scheduling
Use Spot instances for fault-tolerant workloads:
yaml
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: node.kubernetes.io/lifecycle
operator: In
values:
- spot
tolerations:
- key: "kubernetes.io/lifecycle"
operator: "Equal"
value: "spot"
effect: "NoSchedule"
Karpenter
Karpenter is AWS's modern node autoscaler that:
- Provisions nodes just-in-time
- Chooses instance types based on Pod requirements
- Uses Spot when possible
- Can bin-pack efficiently
Covered in depth in Stage 10 (Autoscaling).
Cost Visibility via Scheduling Metrics
| Metric | Meaning |
kube_pod_container_resource_requests | Pod requests |
kube_node_status_allocatable | Node capacity |
kube_pod_status_phase{phase="Pending"} | Pending Pods |
scheduler_schedule_attempts_total | Scheduling attempts |
23. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Scheduling SLA Design
| Target | Architecture |
| 99.9% | Basic affinity, PDBs |
| 99.99% | Topology spread across 3 AZs, anti-affinity, PDBs |
| 99.999% | Multi-region, gang scheduling, chaos-tested |
PART 5: ARCHITECTURE & STRATEGY
24. Multi-Tenant Scheduling Strategy
| Tenant Type | Isolation Strategy |
| Internal teams | Namespaces + priorities + quotas |
| External customers | Separate node pools + taints |
| Hostile tenants | Separate clusters |
| GPU tenants | Dedicated GPU node pools + MIG |
Tenant Isolation via Taints
yaml
# Tenant A nodes
kubectl taint nodes tenant-a-node-1 tenant=a:NoSchedule
# Tenant A Pods
spec:
tolerations:
- key: tenant
operator: Equal
value: a
effect: NoSchedule
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: tenant
operator: In
values: [a]
25. GPU and Specialized Hardware Scheduling
Covered in depth in Stage 12 (GPU Orchestration).
Key patterns:
- Dedicated GPU nodes with taints
- NVIDIA Device Plugin for GPU exposure
- MIG for GPU partitioning
- Topology-aware scheduling for NVLink
26. Compliance & Security for Scheduling
| Framework | Scheduling Requirement |
| PCI-DSS | Network segmentation, dedicated nodes for cardholder data |
| HIPAA | Isolated compute for PHI workloads |
| GDPR | Data residency (EU-only nodes) |
| FedRAMP | Dedicated hardware for controlled data |
Data residency example:
yaml
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: topology.kubernetes.io/region
operator: In
values: [eu-west-1] # Only EU nodes
PART 6: HANDS-ON LABS
Lab 1: Node Selectors and Node Affinity
Goal: Practice node selection.
bash
# Label a node
kubectl get nodes
NODE=$(kubectl get nodes -o jsonpath='{.items[0].metadata.name}')
kubectl label nodes $NODE disktype=ssd
# Pod with node selector
kubectl run selector-pod --image=nginx --overrides='
{
"spec": {
"nodeSelector": {"disktype": "ssd"},
"containers": [{"name": "nginx", "image": "nginx"}]
}
}'
kubectl get pod selector-pod -o wide
kubectl delete pod selector-pod
# Pod with node affinity (required)
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: affinity-pod
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: disktype
operator: In
values: [ssd, nvme]
containers:
- name: nginx
image: nginx
EOF
kubectl get pod affinity-pod -o wide
kubectl delete pod affinity-pod
# Preferred affinity
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: preferred-pod
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: disktype
operator: In
values: [ssd]
containers:
- name: nginx
image: nginx
EOF
kubectl get pod preferred-pod -o wide
kubectl delete pod preferred-pod
# Cleanup
kubectl label nodes $NODE disktype-
Lab 2: Pod Affinity and Anti-Affinity
Goal: Practice pod co-location and spreading.
bash
# Create a "cache" Pod
kubectl run cache --image=redis:7-alpine --labels=app=cache
# Pod with pod affinity (co-locate with cache)
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: affinity-to-cache
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app: cache
topologyKey: kubernetes.io/hostname
containers:
- name: app
image: nginx
EOF
# Both should be on the same node
kubectl get pods -o wide
kubectl delete pod affinity-to-cache
# Pod anti-affinity
kubectl create deployment web --image=nginx --replicas=3
kubectl patch deployment web --type=merge -p='
{
"spec": {
"template": {
"spec": {
"affinity": {
"podAntiAffinity": {
"preferredDuringSchedulingIgnoredDuringExecution": [{
"weight": 100,
"podAffinityTerm": {
"labelSelector": {"matchLabels": {"app": "web"}},
"topologyKey": "kubernetes.io/hostname"
}
}]
}
}
}
}
}
}'
kubectl get pods -l app=web -o wide
# Should be on different nodes if possible
# Cleanup
kubectl delete deployment web
kubectl delete pod cache
Lab 3: Taints and Tolerations
Goal: Practice taints and tolerations.
bash
# Get a node
NODE=$(kubectl get nodes -o jsonpath='{.items[0].metadata.name}')
# Taint the node
kubectl taint nodes $NODE dedicated=gpu:NoSchedule
# Pod without toleration (should fail)
kubectl run no-tol --image=nginx
sleep 10
kubectl get pod no-tol
# Should stay Pending
# Check why
kubectl describe pod no-tol | grep -A3 Events
# Pod with toleration (should schedule)
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: with-tol
spec:
tolerations:
- key: dedicated
operator: Equal
value: gpu
effect: NoSchedule
containers:
- name: nginx
image: nginx
EOF
sleep 10
kubectl get pod with-tol
# Cleanup
kubectl delete pod no-tol with-tol
kubectl taint nodes $NODE dedicated-
Lab 4: Priority Classes and Preemption
Goal: Demonstrate preemption.
bash
# Create priority classes
kubectl apply -f - <<'EOF'
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: low-priority
value: 100
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: high-priority
value: 1000
EOF
# Create a low-priority Pod (hog resources)
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: low-pod
spec:
priorityClassName: low-priority
containers:
- name: hog
image: nginx
resources:
requests:
cpu: "500m"
memory: "500Mi"
EOF
# Create a high-priority Pod
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: high-pod
spec:
priorityClassName: high-priority
containers:
- name: app
image: nginx
resources:
requests:
cpu: "500m"
memory: "500Mi"
EOF
# Watch the low-pod get preempted if resources are tight
# Cleanup
kubectl delete pod low-pod high-pod
kubectl delete priorityclass low-priority high-priority
Lab 5: Topology Spread Constraints
Goal: Distribute Pods across nodes.
bash
# Create a Deployment with topology spread
kubectl apply -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: spread-app
spec:
replicas: 4
selector:
matchLabels:
app: spread-app
template:
metadata:
labels:
app: spread-app
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: spread-app
containers:
- name: app
image: nginx
EOF
# Verify spread
kubectl get pods -l app=spread-app -o wide
# Should be evenly distributed across nodes
# Cleanup
kubectl delete deployment spread-app
Lab 6: Custom Scheduler Plugin
Goal: Understand the Scheduler Framework.
Note: Writing a plugin requires Go and the Kubernetes scheduler framework. This lab is conceptual.
go
// Simple Go plugin outline
package myscheduler
import (
"k8s.io/kubernetes/pkg/scheduler/framework"
)
type MyPlugin struct{}
func (p *MyPlugin) Name() string {
return "MyPlugin"
}
func (p *MyPlugin) Score(
ctx context.Context,
state *framework.CycleState,
pod *v1.Pod,
nodeName string,
) (int64, *framework.Status) {
// Custom scoring logic
return 50, nil
}
// New initializes the plugin
func New(
plArgs runtime.Object,
h framework.Handle,
) (framework.Plugin, error) {
return &MyPlugin{}, nil
}
Register the plugin in KubeSchedulerConfiguration.
Lab 7: 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: impossible
spec:
containers:
- name: app
image: nginx
resources:
requests:
cpu: "1000"
memory: "1Ti"
EOF
sleep 10
kubectl get pod impossible
# Should be Pending
# Diagnose
kubectl describe pod impossible | grep -A10 Events
# Look for FailedScheduling events
# Check node resources
kubectl describe nodes | grep -A5 "Allocated resources"
# Try to fix
kubectl delete pod impossible
# Try with a bad node selector
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: bad-selector
spec:
nodeSelector:
nonexistent: "true"
containers:
- name: app
image: nginx
EOF
sleep 10
kubectl describe pod bad-selector | grep -A5 Events
kubectl delete pod bad-selector
Lab 8: Descheduler in Action
Goal: Rebalance a cluster with the descheduler.
bash
# Create imbalanced workload
kubectl create deployment imbalanced --image=nginx --replicas=6
# Force all replicas onto one node (anti-affinity off)
kubectl patch deployment imbalanced --type=json -p='[
{"op":"add","path":"/spec/template/spec/nodeSelector","value":{"kubernetes.io/hostname":"<node-1-name>"}}
]'
kubectl get pods -l app=imbalanced -o wide
# All on same node
# Install descheduler (simplified - requires more setup in production)
# kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/descheduler/master/kubernetes/base/rbac.yaml
# ... (full descheduler install)
# In production, descheduler would:
# 1. Detect imbalance
# 2. Evict Pods violating policies
# 3. Scheduler re-places them
# Cleanup
kubectl delete deployment imbalanced
Lab 9: Complete Scheduling Strategy
Goal: Build a complete scheduling strategy for a production workload.
bash
# Create namespaces
kubectl create namespace production
# Label nodes
kubectl label nodes --all environment=production
# Taint a "spot" node
# kubectl taint nodes <spot-node> lifecycle=spot:NoSchedule
# Deploy a highly-available workload
kubectl apply -n production -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 6
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
# Priority for production
priorityClassName: system-cluster-critical
# Spread across zones
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: web
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: web
# Prefer SSD nodes
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: environment
operator: In
values: [production]
containers:
- name: web
image: nginx:1.25-alpine
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
readinessProbe:
httpGet:
path: /
port: 80
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: web-pdb
spec:
minAvailable: 4
selector:
matchLabels:
app: web
EOF
# Verify
kubectl get pods -n production -o wide
kubectl get pdb -n production
# Cleanup
kubectl delete namespace production
PART 7: INCIDENT MANAGEMENT
36. Scheduling Incident Post-Mortem Template
text
INCIDENT: Mass Pending Pods - Cluster Outage
DATE: 2024-01-15
DURATION: 45 minutes
SEVERITY: SEV-1
IMPACT: New deployment Pods stuck in Pending. Rollout stalled.
TIMELINE:
14:00 - New deployment rolled out
14:01 - Alert: Pods Pending > 5 minutes
14:03 - On-call acknowledged
14:05 - Identified: all new Pods Pending with "Insufficient cpu"
14:08 - Checked nodes: no node had 2 CPUs free
14:10 - New Pods were requesting 2 CPUs but using 100m
14:15 - Fixed resource requests to 200m
14:20 - Rollout resumed
14:45 - All Pods running
ROOT CAUSE:
Over-requested CPU (2 cores) for pods that needed 200m.
Cluster had capacity but not as a single contiguous 2-core block.
LESSONS LEARNED:
1. Over-requesting wastes cluster capacity.
2. CI should warn on over-requesting.
3. VPA should be used for recommendations.
ACTION ITEMS:
[ ] Deploy VPA to all workloads (Owner: Platform, Due: 2024-01-20)
[ ] Add CI check for over-requesting (Owner: Platform, Due: 2024-01-22)
[ ] Training on resource sizing (Owner: Team, Due: 2024-01-25)
37. On-Call Runbook: Pending Pods
text
SYMPTOM: Pods stuck in Pending.
STEP 1: Confirm
$ kubectl get pods -A | grep Pending
STEP 2: Get the reason
$ kubectl describe pod <pod> | grep -A10 Events
STEP 3: Categorize the reason
"Insufficient cpu/memory":
$ kubectl describe nodes | grep -A5 "Allocated resources"
- Add capacity OR reduce requests
"Taint not tolerated":
$ kubectl describe node <node> | grep Taints
- Add toleration OR remove taint
"Node selector mismatch":
$ kubectl get nodes --show-labels
- Fix selector OR add label
"Affinity mismatch":
$ kubectl get pods -l <selector>
- Relax to preferred OR add node
"Unbound PVC":
$ kubectl get pvc
- Fix PVC or StorageClass
"Unschedulable nodes":
$ kubectl get nodes
- Uncordon
STEP 4: Check scheduler health
$ kubectl get pods -n kube-system -l component=kube-scheduler
$ kubectl logs -n kube-system -l component=kube-scheduler --tail=100
STEP 5: Apply fix
STEP 6: Escalate if unresolved
38. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | All new Pods Pending / scheduler down | 5 min | On-call + Platform + Management |
| SEV-2 | Specific workload stuck Pending | 15 min | On-call + Platform |
| SEV-3 | Slow scheduling | 1 hour | On-call |
| SEV-4 | Configuration warning | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
39. Junior-Level Questions
| Question | Expected Answer |
| What does the scheduler do? | Assigns Pods to nodes |
| What is a taint? | A node marker that repels Pods |
| What is a toleration? | A Pod marker allowing it on tainted nodes |
| What is node affinity? | Advanced node selector with soft/hard rules |
| What is topology spread? | Distributes Pods across failure domains |
40. Mid-Level Questions
| Question | Expected Answer |
| What is a Pending Pod? | Pod scheduled but not yet placed |
| How do you debug a Pending Pod? | kubectl describe → Events |
| What is Pod anti-affinity? | Keep Pods apart |
| What is priority class? | Scheduling priority + preemption |
| What is the default scoring strategy? | LeastAllocated (spread) |
41. Senior-Level Questions
| Question | Expected Answer |
| How do you tune scheduling for HA? | Topology spread + anti-affinity across AZs |
| How do you choose anti-affinity vs topology spread? | Topology spread for HA; anti-affinity for strict |
| What is gang scheduling? | All-or-nothing Pod group scheduling |
| How do you implement bin-packing? | MostAllocated scoring + node affinity |
| What is the Scheduler Framework? | Plugin architecture with 10 extension points |
42. Staff/Principal Questions
| Question | Expected Answer |
| Design a scheduling strategy for a multi-tenant cluster. | Taints + tolerations + quotas + priorities |
| How do you optimize scheduling cost by 40%? | Bin-packing, Spot, Karpenter, right-sizing |
| How do you handle GPU scheduling at scale? | Device plugin, MIG, time-slicing, dedicated node pools |
| How do you migrate from spreading to bin-packing? | Custom scheduler profile, gradual rollout, test |
| How do you ensure data residency via scheduling? | Node labels + affinity + admission policies |
Summary Cheat Sheet
| Concept | Key Takeaway |
| Scheduler | Filter → Score → Bind |
| Node Selector | Simple, hard requirement |
| Node Affinity | Advanced, hard/soft, rich operators |
| Pod Affinity | Co-locate with other Pods |
| Pod Anti-Affinity | Keep apart from other Pods |
| Taint | Node repels Pods |
| Toleration | Pod allows taint |
| NoSchedule | New Pods blocked |
| NoExecute | Existing Pods evicted |
| PriorityClass | Higher priority + preemption |
| Preemption | Evict lower-priority Pods |
| Topology Spread | Even distribution across domains |
| maxSkew | Max difference between domains |
| DoNotSchedule | Hard topology spread |
| ScheduleAnyway | Soft topology spread |
| Scheduler Framework | Plugin architecture |
| Custom Scheduler | Own binary, own rules |
| Scheduler Profile | Multiple schedulers in one binary |
| Descheduler | Rebalance existing Pods |
| NUMA-Aware | Align CPU/memory to NUMA nodes |
| Bin-Packing | MostAllocated scoring |
| Spreading | LeastAllocated scoring (default) |
Stage 6: RBAC, ServiceAccounts & Security — The Comprehensive Guide
PART 1: CORE THEORY
1. The Kubernetes Security Model
Kubernetes security is built on three pillars that are independent and must all be configured correctly. A failure in any one breaks the whole chain.
The Three Pillars
text
┌─────────────────────────────────────────────────────────────┐
│ KUBERNETES SECURITY MODEL │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ AUTHENTICATION (AuthN) │ │
│ │ "Who are you?" │ │
│ │ → Certificates, tokens, OIDC, webhooks │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ AUTHORIZATION (AuthZ) │ │
│ │ "What can you do?" │ │
│ │ → RBAC, ABAC, Node, Webhook │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ ADMISSION CONTROL │ │
│ │ "Should we allow this?" │ │
│ │ → Mutating → Validating webhooks/policies │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Key Principles
| Principle | Meaning |
| Zero-Trust | No implicit trust; verify everything |
| Least Privilege | Minimum permissions necessary |
| Defense in Depth | Multiple independent layers |
| Separation of Duties | No single role has all power |
2. Authentication
Authentication verifies the identity of the caller. The API server supports several methods.
Authentication Methods
| Method | Use Case |
| X.509 Client Certificates | Human admins, kubelet |
| ServiceAccount Tokens | Workloads inside the cluster |
| OIDC | Enterprise SSO (Okta, Azure AD, Google) |
| Webhook Token Authentication | External auth service |
| Authenticating Proxy | Header-based (for proxies) |
| Bootstrap Tokens | Node bootstrap |
| Static Token File | Legacy (deprecated) |
X.509 Client Certificates
The most common method for admins and kubelets. The Common Name (CN) becomes the username; Organization (O) becomes the group.
text
Subject: CN=alice, O=developers, O=engineering
│ │
│ └── Groups: [developers, engineering]
└── Username: alice
The API server verifies the certificate is signed by its CA.
ServiceAccount Tokens
Every Pod can have a ServiceAccount. Kubernetes mints a JWT token for it.
Pre-1.21: Static, never-expiring tokens.
1.21+ (projected tokens): Time-limited, audience-bound, auto-rotated.
yaml
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
serviceAccountName: my-sa
containers:
- name: app
image: myapp
volumeMounts:
- name: token
mountPath: /var/run/secrets/kubernetes.io/serviceaccount
readOnly: true
volumes:
- name: token
projected:
sources:
- serviceAccountToken:
path: token
expirationSeconds: 3600
audience: https://kubernetes.default.svc
The token is mounted at /var/run/secrets/kubernetes.io/serviceaccount/token.
Key fact: By default, every Pod gets a ServiceAccount token. This is a security concern for Pods that don't need cluster API access. Disable with automountServiceAccountToken: false.
OIDC (OpenID Connect)
Enterprise SSO integration. The API server validates tokens from an OIDC provider.
yaml
# kube-apiserver flags
--oidc-issuer-url=https://accounts.google.com
--oidc-client-id=kubernetes
--oidc-username-claim=email
--oidc-groups-claim=groups
Anonymous Requests
By default, unauthenticated requests are treated as system:anonymous (group system:unauthenticated). This is normally denied by RBAC, but can be explicitly allowed.
Security tip: Disable anonymous auth unless you have a specific reason:
text
--anonymous-auth=false
Username Conventions
| Prefix | Meaning |
system: | Kubernetes internal |
system:serviceaccount:<ns>:<name> | ServiceAccount |
system:node:<name> | Kubelet |
system:apiserver | API server |
| (no prefix) | External user |
Authentication Best Practices
| Practice | Why |
| Use OIDC for humans | Centralized, auditable |
| Rotate client certificates | Short-lived, limited blast radius |
| Disable static tokens | Deprecated, hard to rotate |
| Disable anonymous auth | Prevent unauthorized access |
| Use bound ServiceAccount tokens | Auto-rotated, audience-scoped |
| Audit all authentication | Detect anomalies |
3. Authorization
Once authenticated, Kubernetes checks if the user is authorized to perform the requested action.
Authorization Modes
| Mode | Description | Use Case |
| RBAC | Role-Based Access Control | Default, recommended |
| ABAC | Attribute-Based Access Control | Legacy, file-based |
| Node | Node authorizer | Kubelet authorization |
| Webhook | External authorization | Custom policies |
| AlwaysAllow | Everything is allowed | ❌ Never in production |
| AlwaysDeny | Everything is denied | Testing |
Multiple Authorization Modes
The API server checks modes in order and uses the first one that makes a decision. If RBAC denies, but Webhook allows, the request is allowed (Webhook is checked last).
Common configuration:
text
--authorization-mode=Node,RBAC
The RBAC Verb Set
| Verb | Action |
| get | Read one resource |
| list | List resources |
| watch | Watch for changes |
| create | Create new |
| update | Update existing (full) |
| patch | Update (partial) |
| delete | Delete one |
| deletecollection | Delete many |
The RBAC Resource Set
| Resource | Example |
| pods | Core Pod resources |
| pods/log | Pod subresource (logs) |
| pods/exec | Pod subresource (exec) |
| deployments | Apps group |
| secrets | Sensitive |
| nodes | Cluster-level |
| configmaps | Non-sensitive config |
4. RBAC
RBAC (Role-Based Access Control) is the default and recommended authorization mode in Kubernetes. It grants permissions via Roles and Bindings.
The Four Objects
| Object | Scope | Purpose |
| Role | Namespace | Permissions within a namespace |
| ClusterRole | Cluster | Permissions cluster-wide |
| RoleBinding | Namespace | Bind Role or ClusterRole to subjects |
| ClusterRoleBinding | Cluster | Bind ClusterRole to subjects cluster-wide |
Role (Namespace-Scoped)
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: production
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["pods/log"]
verbs: ["get"]
ClusterRole (Cluster-Scoped)
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: node-reader
rules:
- apiGroups: [""]
resources: ["nodes"]
verbs: ["get", "list", "watch"]
RoleBinding
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: alice-pod-reader
namespace: production
subjects:
- kind: User
name: alice
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
ClusterRoleBinding
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: alice-node-reader
subjects:
- kind: User
name: alice
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: node-reader
apiGroup: rbac.authorization.k8s.io
Subjects
| Kind | Example |
| User | alice, bob@example.com |
| Group | developers, system:masters |
| ServiceAccount | default/my-sa (namespace/name) |
The Secret to RBAC: Bindings vs Permissions
RoleBindings cannot grant permissions the Role doesn't have. You can bind a ClusterRole to a namespace using a RoleBinding — this grants the ClusterRole's permissions within that namespace only.
Example: Bind cluster-admin ClusterRole to a RoleBinding in namespace production → the user has admin permissions within production only.
Default ClusterRoles
Kubernetes ships with built-in ClusterRoles:
| ClusterRole | Purpose |
| cluster-admin | Full cluster access |
| admin | Namespace admin (most resources) |
| edit | Edit most resources (no RBAC) |
| view | Read-only (no Secrets) |
Default ServiceAccounts
Each namespace has a default ServiceAccount. Pods that don't specify one use it.
Security tip: Don't grant permissions to default; create per-workload ServiceAccounts.
RBAC Decision Logic
When a request comes in:
- Gather all Roles/ClusterRoles bound to the user via RoleBindings/ClusterRoleBindings.
- Check if any rule allows the request.
- If yes → allow. If no → deny.
Key insight: RBAC is additive. There are no deny rules. You can only grant permissions, not remove them.
RBAC Verbs and Resources (Common Combinations)
| Need | Role Rule |
| Read Pods | resources: ["pods"], verbs: ["get", "list", "watch"] |
| Read Pod logs | resources: ["pods/log"], verbs: ["get"] |
| Exec into Pods | resources: ["pods/exec"], verbs: ["create"] |
| Port forward | resources: ["pods/portforward"], verbs: ["create"] |
| List Secrets | resources: ["secrets"], verbs: ["list"] |
| Deploy | resources: ["deployments"], verbs: ["create", "update"] |
| Delete namespace | resources: ["namespaces"], verbs: ["delete"] |
RBAC Anti-Patterns
| Anti-Pattern | Risk |
| cluster-admin for humans | Full cluster compromise |
Wildcard verbs (*) | Unintended permissions |
Wildcard resources (*) | Unintended scope |
Binding cluster-admin via RoleBinding | Namespace-wide admin |
| default ServiceAccount with permissions | Every Pod gets it |
| No RBAC auditing | Drift, unused perms |
RBAC Verification
bash
# Check what you can do
kubectl auth can-i --list
# Check specific permission
kubectl auth can-i create pods
kubectl auth can-i delete deployments -n production
# Check as another user
kubectl auth can-i list secrets --as=system:serviceaccount:default:my-sa
kubectl auth can-i list secrets --as=alice
# Check cluster-wide
kubectl auth can-i list pods --all-namespaces
The kubectl who-can Plugin
bash
# Install krew plugin
kubectl krew install who-can
# Check who can do something
kubectl who-can list secrets
kubectl who-can delete pods -n production
5. ServiceAccounts
A ServiceAccount is an identity for processes running in Pods. It's how Pods authenticate to the Kubernetes API.
Creating a ServiceAccount
yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-app-sa
namespace: production
bash
kubectl create serviceaccount my-app-sa -n production
Using a ServiceAccount in a Pod
yaml
apiVersion: v1
kind: Pod
metadata:
name: my-app
spec:
serviceAccountName: my-app-sa
automountServiceAccountToken: false # Best practice
containers:
- name: app
image: my-app:1.0
The ServiceAccount Token
Pre-1.21 (legacy): Static Secret-backed tokens.
1.21+ (projected): Time-limited, audience-bound tokens.
The token is mounted at:
text
/var/run/secrets/kubernetes.io/serviceaccount/token
/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
/var/run/secrets/kubernetes.io/serviceaccount/namespace
Disabling Auto-Mounting
By default, every Pod gets a ServiceAccount token. If your Pod doesn't need to call the Kubernetes API:
yaml
spec:
automountServiceAccountToken: false
Or disable at the ServiceAccount level:
yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: no-api-sa
automountServiceAccountToken: false
Why this matters: A leaked token allows an attacker to make API calls with the Pod's identity. If the Pod doesn't need the API, don't give it a token.
Binding a ServiceAccount to RBAC
ServiceAccounts can be subjects in RoleBindings:
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: my-app-pod-reader
namespace: production
subjects:
- kind: ServiceAccount
name: my-app-sa
namespace: production
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
Workload Identity (Cloud)
ServiceAccounts are also used for cloud identity:
- AWS: IRSA (IAM Roles for Service Accounts)
- GCP: Workload Identity
- Azure: Azure AD Workload Identity
These allow Pods to assume cloud IAM roles without static credentials.
Best Practices
| Practice | Why |
| One ServiceAccount per workload | Least privilege |
| Disable auto-mount when not needed | Reduce attack surface |
| Use projected tokens | Auto-rotated |
| Bind to minimal RBAC | Least privilege |
| Audit ServiceAccount usage | Detect anomalies |
Never use default | Shared across namespace |
| Use workload identity | No static cloud credentials |
PART 2: ADVANCED CONCEPTS
6. Pod Security Standards
Pod Security Standards (PSS) define three security profiles that namespace admins can enforce.
The Three Levels
| Level | Restrictiveness | Use Case |
| Privileged | Unrestricted | System workloads |
| Baseline | Minimally restrictive | Most workloads |
| Restricted | Heavily restrictive | Security-critical |
Privileged (No Restrictions)
Everything allowed. Only for cluster-admin workloads (CNI, monitoring, system components).
Baseline (Common Restrictions)
Blocks:
- Privileged containers
- Host namespaces (hostNetwork, hostPID, hostIPC)
- hostPath volumes
- Host ports
- Unsafe capabilities (SYS_ADMIN, NET_ADMIN, etc.)
- Unsafe sysctls
- Privilege escalation
Allows:
- Running as root
- Any container user
- Read-write root filesystem
Restricted (Maximum Security)
Everything in Baseline, plus:
runAsNonRoot: truerequiredallowPrivilegeEscalation: falserequiredcapabilities.drop: [ALL]requiredseccompProfile.type: RuntimeDefaultorLocalhostrequiredreadOnlyRootFilesystemrecommended
Baseline vs Restricted Comparison
| Setting | Baseline | Restricted |
| Privileged | ❌ | ❌ |
| Host namespaces | ❌ | ❌ |
| hostPath | ❌ | ❌ |
| Host ports | ❌ | ❌ |
| Capabilities | Limited | Drop ALL |
| Privilege escalation | ❌ | ❌ |
| Non-root | Optional | Required |
| Read-only rootfs | Optional | Recommended |
| seccomp | Optional | Required |
7. Pod Security Admission
Pod Security Admission (PSA) is the built-in admission controller that enforces PSS.
Enforcing PSS via Namespace Labels
bash
kubectl label namespace production \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/warn=restricted
The Three Modes
| Mode | Behavior |
| enforce | Reject violating Pods |
| audit | Log violations |
| warn | Show warning to user |
Version Pinning
yaml
pod-security.kubernetes.io/enforce-version: v1.30
pod-security.kubernetes.io/enforce-version: latest
Pinning prevents surprises when the cluster is upgraded.
Migration Path
Recommended migration:
- Audit only:
audit=restricted, no enforcement - Warn only:
warn=restricted - Enforce baseline:
enforce=baseline - Enforce restricted:
enforce=restricted
Exempting Namespaces
Some namespaces (kube-system, CNI plugins) need privileged access. Use a label:
yaml
pod-security.kubernetes.io/enforce: privileged
Or exclude at the API server:
text
--admission-control-config-file=/etc/kubernetes/admission-config.yaml
What PSS Doesn't Cover
PSS is limited to a specific set of security controls. For deeper policies (e.g., required labels, image registry whitelist), use Kyverno or OPA Gatekeeper.
8. Admission Webhooks
Admission webhooks are HTTP callbacks from the API server to external services. They run during admission.
Mutating vs Validating
| Type | Can Modify? | Order |
| Mutating | ✅ Yes | First |
| Validating | ❌ No | Second |
Failure Policy
| Policy | Behavior | When to Use |
| Fail | Reject if webhook unreachable | Security-critical |
| Ignore | Allow if webhook unreachable | Optional features |
Webhook Timeout
Default: 10 seconds (configurable up to 30).
The Recovery Pattern
If a webhook is blocking cluster recovery:
bash
# Temporarily change failurePolicy to Ignore
kubectl patch validatingwebhookconfiguration <name> --type='json' \
-p='[{"op":"replace","path":"/webhooks/0/failurePolicy","value":"Ignore"}]'
⚠️ This disables enforcement. Use only during confirmed outages.
Webhook Anti-Patterns
| Anti-Pattern | Risk |
| failurePolicy: Fail with no HA | Webhook outage → cluster outage |
| Webhooks for every resource | Massive overhead |
| Slow webhooks (> 1s) | Cluster-wide slowdown |
| No timeout | Requests hang |
| Broad resource scope | Unintended side effects |
9. OPA Gatekeeper
OPA (Open Policy Agent) Gatekeeper is a policy engine that uses Rego (a declarative policy language).
Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ OPA GATEKEEPER │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Gatekeeper Controller │ │
│ │ • Watches ConstraintTemplates and Constraints │ │
│ │ • Manages policies │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Gatekeeper Webhook │ │
│ │ • Receives admission requests │ │
│ │ • Evaluates against Rego policies │ │
│ │ • Returns allow/deny │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
The Two CRDs
| CRD | Purpose |
| ConstraintTemplate | Defines a policy type (Rego code) |
| Constraint | Instance of a policy with parameters |
ConstraintTemplate Example
yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
crd:
spec:
names:
kind: K8sRequiredLabels
validation:
openAPIV3Schema:
properties:
labels:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredlabels
violation[{"msg": msg}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.parameters.labels[_]}
missing := required - provided
count(missing) > 0
msg := sprintf("Missing labels: %v", [missing])
}
Constraint Example
yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-team-label
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
namespaces: ["production"]
parameters:
labels: ["team", "environment"]
Common OPA Gatekeeper Use Cases
| Policy | Purpose |
| Required labels | Enforce metadata |
| Allowed registries | Image policy |
| No privileged | Pod security |
| Resource limits | Governance |
| Namespace restrictions | Multi-tenancy |
OPA Rego vs YAML
| Aspect | OPA/Rego | Kyverno/YAML |
| Language | Rego (custom DSL) | YAML |
| Power | Very high | High |
| Learning curve | Steep | Gentle |
| Ecosystem | CNCF | Kyverno |
| Best for | Complex policies | Kubernetes-native |
10. Kyverno
Kyverno is a Kubernetes-native policy engine. Policies are written in YAML (no custom DSL).
The Two CRDs
| CRD | Purpose |
| ClusterPolicy | Cluster-wide policy |
| Policy | Namespace-scoped policy |
Kyverno Rule Types
| Type | Purpose |
| validate | Accept/deny resources |
| mutate | Modify resources |
| generate | Create resources |
| verifyImages | Verify image signatures |
Validation Policy Example
yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-non-root
spec:
validationFailureAction: Enforce
background: true
rules:
- name: check-runAsNonRoot
match:
any:
- resources:
kinds:
- Pod
validate:
message: "Containers must set runAsNonRoot: true"
pattern:
spec:
containers:
- securityContext:
runAsNonRoot: true
Mutation Policy Example
yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-default-labels
spec:
rules:
- name: add-team-label
match:
any:
- resources:
kinds:
- Pod
mutate:
patchStrategicMerge:
metadata:
labels:
team: unknown
Generate Policy Example
yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: generate-default-networkpolicy
spec:
rules:
- name: create-default-deny
match:
any:
- resources:
kinds:
- Namespace
generate:
synchronize: true
kind: NetworkPolicy
name: default-deny
namespace: "{{request.object.metadata.name}}"
data:
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
Kyverno Validation Failure Actions
| Action | Behavior |
| Enforce | Block violation |
| Audit | Log only (report) |
Kyverno Best Practices
| Practice | Why |
| Start with Audit | Don't break workloads |
| Test in staging | Policies can have bugs |
| Version-control policies | GitOps |
Use background: true | Retroactive enforcement |
Set validationFailureAction | Enforce vs audit |
| Exclude system namespaces | CNI, kube-system |
11. Image Policy
Image policy governs which container images are allowed in the cluster.
The Three Layers
| Layer | Tool | Purpose |
| Registry | Harbor, ECR | Store scanned images |
| Admission | Kyverno verifyImages | Verify signatures at deploy |
| Runtime | Falco, Tetragon | Detect anomalous behavior |
Image Signature Verification with cosign
Sign an image:
bash
cosign sign --key cosign.key myregistry/myapp:v1.0.0
Verify in Kyverno:
yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: verify-image-signature
spec:
validationFailureAction: Enforce
rules:
- name: verify-cosign-signature
match:
any:
- resources:
kinds:
- Pod
verifyImages:
- imageReferences:
- "myregistry.example.com/*"
attestors:
- entries:
- keys:
publicKeys: |-
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
-----END PUBLIC KEY-----
The Full Image Policy Pipeline
text
Developer → Build Image → Trivy Scan → Fail on CRITICAL → Push
│
▼
Cosign Sign
│
▼
Registry (Harbor/ECR)
│
▼
Admission (Kyverno)
Verify Signature
│
▼
Deploy to Cluster
│
▼
Runtime (Falco/Tetragon)
Image Policy Best Practices
| Practice | Why |
| Sign all images | Prove provenance |
| Scan before sign | Block vulnerabilities |
| Verify at admission | Reject unsigned |
| Use SBOM | Supply chain visibility |
| Pin by digest | Immutability |
Block :latest | Non-deterministic |
12. Secrets Management
Secrets in Kubernetes are base64-encoded, not encrypted by default. Production requires external secret management.
The Problem with Native Secrets
| Issue | Impact |
| Base64 (not encryption) | Anyone with read access can decode |
| etcd storage | Depends on etcd encryption |
| No rotation | Manual, error-prone |
| In Git | Leaked into version history |
| In env vars | Visible in docker inspect |
Encryption at Rest
Enable etcd encryption at rest:
yaml
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
- resources:
- secrets
- configmaps
providers:
- aescbc:
keys:
- name: key1
secret: <base64-key>
- identity: {}
Pass to kube-apiserver: --encryption-provider-config=/etc/kubernetes/encryption-config.yaml.
External Secrets Operator
External Secrets Operator (ESO) syncs secrets from external stores to Kubernetes.
Supported stores:
- AWS Secrets Manager
- AWS Systems Manager Parameter Store
- GCP Secret Manager
- Azure Key Vault
- HashiCorp Vault
- 1Password
- Doppler
Example ExternalSecret:
yaml
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: db-secret
spec:
refreshInterval: 1h
secretStoreRef:
name: aws-secrets-manager
kind: SecretStore
target:
name: db-secret
data:
- secretKey: password
remoteRef:
key: prod/db/password
Sealed Secrets
Sealed Secrets encrypts secrets so they can be safely committed to Git.
bash
# Encrypt
kubeseal --format=yaml < secret.yaml > sealed-secret.yaml
# The sealed secret is safe to commit
git add sealed-secret.yaml
# Sealed Secrets controller decrypts in-cluster
kubectl apply -f sealed-secret.yaml
SOPS (Secrets OPerationS)
SOPS encrypts YAML/JSON files using cloud KMS. Works with GitOps.
bash
# Encrypt
sops --encrypt --age <age-key> secret.yaml > secret.enc.yaml
# Decrypt
sops --decrypt secret.enc.yaml
Vault Integration
HashiCorp Vault is the enterprise standard. Integration methods:
| Method | Description |
| Vault Agent Injector | Sidecar injects secrets |
| Vault Secrets Operator | Syncs Vault to K8s Secrets |
| CSI Secrets Store | Mounts secrets as volumes |
| Vault API | Direct API access |
Secrets Management Comparison
| Approach | Complexity | Security | Use Case |
| Native Secrets | Low | ⚠️ Base64 | Dev/test |
| Encryption at rest | Medium | ✅ | Basic hardening |
| Sealed Secrets | Low | ✅ | GitOps |
| SOPS | Low | ✅ | GitOps + KMS |
| External Secrets | Medium | ✅✅ | Multi-cloud |
| Vault | High | ✅✅✅ | Enterprise |
13. SecurityContext Deep Dive
SecurityContext is where you configure container security at the Pod and container level.
Pod-Level SecurityContext
yaml
spec:
securityContext:
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
runAsNonRoot: true
fsGroupChangePolicy: "OnRootMismatch"
seccompProfile:
type: RuntimeDefault
supplementalGroups: [2000]
sysctls:
- name: net.ipv4.ip_unprivileged_port_start
value: "0"
Container-Level SecurityContext
yaml
spec:
containers:
- name: app
securityContext:
runAsUser: 1000
runAsGroup: 1000
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
privileged: false
capabilities:
drop: ["ALL"]
add: ["NET_BIND_SERVICE"]
seccompProfile:
type: RuntimeDefault
procMount: Default
Key Security Context Fields
| Field | Purpose |
| runAsUser | UID to run container |
| runAsGroup | GID to run container |
| runAsNonRoot | Require non-root |
| fsGroup | Volume ownership group |
| supplementalGroups | Extra groups |
| allowPrivilegeEscalation | Prevent suid, setuid |
| readOnlyRootFilesystem | Immutable rootfs |
| privileged | Full privileges (never) |
| capabilities | Linux capabilities |
| seccompProfile | Syscall filtering |
| procMount | Proc filesystem |
The Complete Hardened SecurityContext
yaml
apiVersion: v1
kind: Pod
metadata:
name: hardened
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
seccompProfile:
type: RuntimeDefault
automountServiceAccountToken: false
containers:
- name: app
image: myapp:1.0
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
privileged: false
capabilities:
drop: ["ALL"]
resources:
limits:
cpu: 500m
memory: 256Mi
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}
This is the gold standard for workload hardening.
14. Audit Logging
Audit logging records every request to the API server with who/what/when/where.
Audit Policy
yaml
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
# Log all secrets access (RequestResponse = full body)
- level: RequestResponse
resources:
- group: ""
resources: ["secrets"]
verbs: ["get", "list", "watch", "create", "update", "delete"]
# Log RBAC changes
- level: Request
resources:
- group: "rbac.authorization.k8s.io"
resources: ["roles", "clusterroles", "rolebindings", "clusterrolebindings"]
# Log all authentication failures
- level: Metadata
omitStages:
- RequestReceived
users: ["system:anonymous"]
Audit Levels
| Level | What's Logged |
| None | Nothing |
| Metadata | Who, what, when — no body |
| Request | Metadata + request body |
| RequestResponse | Metadata + request + response |
API Server Flags
text
--audit-policy-file=/etc/kubernetes/audit-policy.yaml
--audit-log-path=/var/log/kubernetes/audit.log
--audit-log-maxage=30
--audit-log-maxbackup=10
--audit-log-maxsize=100
What to Audit
| Resource | Level | Why |
| Secrets | RequestResponse | Track access |
| RBAC | Request | Detect privilege changes |
| Authentication failures | Metadata | Detect attacks |
| Exec/port-forward | Metadata | Track access |
| Pod creation | Metadata | Workload tracking |
Audit Log Example
json
{
"kind": "Event",
"apiVersion": "audit.k8s.io/v1",
"level": "RequestResponse",
"timestamp": "2024-01-15T14:03:00Z",
"user": {
"username": "alice",
"groups": ["developers"]
},
"sourceIPs": ["10.0.0.1"],
"verb": "get",
"resource": {
"group": "",
"resource": "secrets",
"namespace": "production",
"name": "db-password"
},
"responseStatus": {
"code": 200
}
}
Audit Log Best Practices
| Practice | Why |
| Log Secrets access | Detect data exfiltration |
| Log RBAC changes | Detect privilege escalation |
| Ship to SIEM | Centralized analysis |
| Retain 90+ days | Compliance |
| Alert on anomalies | Detect attacks |
| Protect audit logs | Append-only storage |
15. Network Policies
Network Policies are the firewall for Pods. Covered in depth in Stage 7 (Networking), but essential for security.
Default Deny
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
Allow Specific Traffic
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: production
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
Egress (Often Forgotten)
yaml
spec:
policyTypes:
- Egress
egress:
- to:
- namespaceSelector:
matchLabels:
name: kube-system
ports:
- protocol: UDP
port: 53
The default is allow-all egress. Attackers use egress for C2, exfiltration. Always define egress policies.
16. IRSA and Workload Identity
IRSA (IAM Roles for Service Accounts) allows Pods to assume AWS IAM roles without static credentials.
How IRSA Works
text
1. Cluster has OIDC provider configured
2. AWS IAM trusts the OIDC provider
3. A ServiceAccount is mapped to an IAM role
4. Pod uses its ServiceAccount token
5. AWS SDK exchanges the token for temporary IAM credentials
6. Pod makes AWS API calls with IAM role
Setting Up IRSA (AWS)
Step 1: Create OIDC provider for the cluster
bash
eksctl utils associate-iam-oidc-provider --cluster my-cluster --approve
Step 2: Create IAM role with trust policy
json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/ABC123"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"oidc.eks.us-east-1.amazonaws.com/id/ABC123:sub": "system:serviceaccount:production:my-app-sa",
"oidc.eks.us-east-1.amazonaws.com/id/ABC123:aud": "sts.amazonaws.com"
}
}
}
]
}
Step 3: Annotate ServiceAccount
yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-app-sa
namespace: production
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::123456789:role/my-app-role
Step 4: Use in Pod
yaml
spec:
serviceAccountName: my-app-sa
containers:
- name: app
image: my-app:1.0
# AWS SDK automatically uses IRSA credentials
Comparison
| Cloud | Name | Mechanism |
| AWS | IRSA | OIDC + IAM Role |
| GCP | Workload Identity | GKE SA + GCP SA |
| Azure | Azure AD Workload Identity | OIDC + Azure AD |
Best Practices
| Practice | Why |
| One SA per workload | Least privilege |
| One IAM role per SA | Audit clarity |
| Scoped IAM policies | Least privilege |
| No static credentials | Rotation-free |
| Audit IAM role usage | CloudTrail |
PART 3: PRODUCTION FAILURE MODES
17. Top 10 Kubernetes Security Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | Over-privileged SA | Lateral movement | Broad RBAC | Least privilege |
| 2 | cluster-admin for humans | Full compromise | Convenience | OIDC + scoped RBAC |
| 3 | Secrets in Git | Credentials leaked | No secrets management | Sealed Secrets, SOPS |
| 4 | Privileged containers | Container escape | No PSS enforcement | PSA restricted |
| 5 | No NetworkPolicy | Lateral movement | Default allow-all | Default deny |
| 6 | Anonymous auth enabled | Unauthorized access | Default config | Disable |
| 7 | Webhook failurePolicy: Fail | Cluster outage | Webhook down | HA webhook |
| 8 | Unrotated certificates | Auth failures | No rotation | kubeadm certs renew |
| 9 | No audit logging | Can't investigate | Not configured | Enable audit logs |
| 10 | Image without signature verification | Backdoored image | No verifyImages | Kyverno verify |
18. Security Incident Runbook
"Suspected RBAC Breach" — Step-by-Step
text
STEP 1: Identify the incident
# Alert source: audit logs, anomaly detection
# Verify legitimacy
STEP 2: Isolate the affected identity
# If ServiceAccount:
$ kubectl delete sa <sa-name> -n <namespace>
# If user:
# Revoke credentials at the IdP
STEP 3: Audit what the identity did
$ kubectl get events --field-selector reason=RBACDenied
# Or check audit logs
# Filter by the identity
STEP 4: Identify the breach vector
# Was the SA over-privileged?
$ kubectl get rolebindings,clusterrolebindings -A -o json | \
jq '.items[] | select(.subjects[]?.name=="<sa-name>")'
# Or for a user:
$ kubectl auth can-i --list --as=<user>
STEP 5: Check for lateral movement
# What else did the identity access?
# Check audit logs for all requests
STEP 6: Rotate compromised credentials
# Delete ServiceAccount and recreate
# Rotate any tokens
STEP 7: Fix the RBAC misconfiguration
# Remove over-privileged roles
# Apply least privilege
STEP 8: Post-incident
# Document
# Update policies
# Notify stakeholders
STEP 9: Escalate
# Security team, management
Indicators of Compromise (IoCs)
| Indicator | Where to Look |
| Unexpected RBAC changes | Audit logs |
| Anomalous API access | Audit logs |
| New ServiceAccount created | Audit logs |
| ClusterRoleBinding created | Audit logs |
| Secrets accessed outside hours | Audit logs |
Unexpected kubectl exec | Audit logs |
| New IAM role assumption | CloudTrail (AWS), Cloud Audit Logs (GCP) |
19. Blast Radius Analysis
What Happens When Security Fails?
| Component | Impact | Severity |
| cluster-admin compromised | Full cluster takeover | SEV-1 |
| ServiceAccount compromised | Depends on RBAC | SEV-1 to SEV-3 |
| Secret leaked | Depends on secret scope | SEV-1 to SEV-3 |
| Privileged container escape | Node compromise | SEV-1 |
| Image backdoor | Full service compromise | SEV-1 |
| RBAC misconfiguration | Unintended access | SEV-2 |
| Webhook down | Blocked admissions | SEV-2 |
Mitigation Strategies
| Strategy | Implementation |
| Least privilege RBAC | Minimal permissions |
| OIDC for humans | Centralized identity |
| Pod Security Standards | Restricted enforcement |
| Network Policies | Default deny |
| Image signing | cosign + admission |
| Audit logging | Centralized SIEM |
| Secret management | Vault, External Secrets |
| Runtime security | Falco, Tetragon |
PART 4: CAPACITY PLANNING & COST MODELING
20. Policy Engine Overhead Modeling
Webhook Overhead
| Webhook Type | Latency | Impact |
| OPA Gatekeeper | 5-50ms | Per admission |
| Kyverno | 5-30ms | Per admission |
| Custom webhook | Varies | Depends on logic |
The Admission Bottleneck
Every admission request goes through:
- Mutating webhooks
- Schema validation
- Validating admission policies
- Validating webhooks
Impact: For a cluster with 10 webhooks, each admission has ~50-200ms overhead.
Scaling Considerations
| Cluster Size | Webhook Replicas |
| < 100 nodes | 2 replicas |
| 100-500 nodes | 3-5 replicas |
| > 500 nodes | 5-10 replicas + PDB |
Overhead Mitigation
| Strategy | Impact |
| Scope webhooks narrowly | Fewer matches |
| Cache decisions | Lower latency |
| Use ValidatingAdmissionPolicy (CEL) | In-process, faster |
| Batch operations | Fewer admissions |
21. Security Tooling Cost Analysis
Runtime Security Cost
| Tool | Deployment | Cost per Node |
| Falco (self-hosted) | DaemonSet | Infrastructure only |
| Tetragon | DaemonSet | Infrastructure only |
| Datadog Security | DaemonSet | ~$30/month |
| Sysdig Secure | DaemonSet | Enterprise pricing |
| Aqua | Multiple | Enterprise pricing |
Policy Engine Cost
| Tool | Cost |
| OPA Gatekeeper | Free (open source) |
| Kyverno | Free (open source) |
| Kyverno Enterprise | Commercial |
| Styra DAS | Commercial (OPA management) |
Secrets Management Cost
| Tool | Cost |
| Kubernetes Secrets | Free |
| Sealed Secrets | Free |
| SOPS | Free (KMS costs) |
| External Secrets Operator | Free (backend costs) |
| HashiCorp Vault | OSS free / Enterprise pricing |
| AWS Secrets Manager | $0.40/secret/month + API calls |
The TCO of a Security Incident
| Incident Type | Estimated Cost |
| RBAC breach | $100K - $1M+ |
| Secret leak | $500K - $5M+ |
| Ransomware | $1M - $10M+ |
| Supply chain | $10M+ (SolarWinds scale) |
Security tooling is cheap compared to incidents.
22. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Security SLA Design
| Target | Architecture |
| 99.9% | Basic RBAC, PSA baseline |
| 99.99% | RBAC + PSA restricted + Kyverno + Falco |
| 99.999% | Above + zero-trust, mTLS, image signing, chaos-tested |
HA for Security Components
| Component | HA Requirement |
| Webhooks | 3+ replicas, PDB |
| OPA Gatekeeper | 3+ replicas |
| Kyverno | 3+ replicas |
| Vault | 3+ node cluster |
| Audit log backend | Replicated |
PART 5: ARCHITECTURE & STRATEGY
23. Zero-Trust Kubernetes Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ ZERO-TRUST ARCHITECTURE │
│ │
│ Identity │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ • OIDC for humans │ │
│ │ • SPIFFE/SPIRE for workloads │ │
│ │ • IRSA/Workload Identity for cloud │ │
│ │ • Bound ServiceAccount tokens (short-lived) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Authorization │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ • RBAC (least privilege) │ │
│ │ • ValidatingAdmissionPolicy (CEL) │ │
│ │ • Kyverno/OPA for complex policies │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Network │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ • Default-deny NetworkPolicies │ │
│ │ • mTLS between all services (Istio, Linkerd) │ │
│ │ • Egress restrictions │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Runtime │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ • Non-root, read-only rootfs │ │
│ │ • Drop ALL capabilities │ │
│ │ • seccomp RuntimeDefault │ │
│ │ • PSA restricted │ │
│ │ • Falco/Tetragon detection │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Supply Chain │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ • Signed images (cosign) │ │
│ │ • Verified at admission │ │
│ │ • SBOM generated │ │
│ │ • SLSA provenance │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Data │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ • Encryption at rest (etcd) │ │
│ │ • External secrets (Vault, ESO) │ │
│ │ • Audit logging to SIEM │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
24. Multi-Tenant Security Architecture
| Isolation Level | Mechanism |
| Soft | Namespaces + RBAC + NetworkPolicy + Quotas |
| Medium | Above + Pod Security Standards (restricted) |
| Hard | vCluster or separate clusters |
| Strongest | Separate clusters, separate cloud accounts |
Namespace Isolation Checklist
- □ RBAC: Namespace-scoped roles
- □ NetworkPolicy: Default deny
- □ ResourceQuota: Per-namespace limits
- □ LimitRange: Default limits
- □ PodSecurity: Restricted
- □ ServiceAccounts: Per-workload
- □ Secrets: Namespace-scoped
- □ Image policy: Verified images
25. Compliance & Security Frameworks
| Framework | K8s Requirement |
| PCI-DSS | RBAC, audit logs, encryption, network segmentation |
| HIPAA | Audit trails, access controls, encryption |
| SOC2 | Change management, monitoring, incident response |
| GDPR | Data residency, access controls, right to erasure |
| FedRAMP | FIPS 140-2, SELinux, no privileged, STIG |
CIS Kubernetes Benchmark (Key Items)
- □ Anonymous auth disabled
- □ RBAC enabled
- □ Client cert auth for admins
- □ Audit logging enabled
- □ etcd encryption at rest
- □ No privileged containers
- □ No root in containers
- □ PSA restricted
- □ NetworkPolicies default deny
- □ Image policy enforced
PART 6: HANDS-ON LABS
Lab 1: RBAC Basics
Goal: Create Roles, RoleBindings, ServiceAccounts.
bash
# Create a namespace
kubectl create namespace rbac-lab
# Create a ServiceAccount
kubectl create serviceaccount reader -n rbac-lab
# Create a Role
kubectl apply -n rbac-lab -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list", "watch"]
EOF
# Create a RoleBinding
kubectl apply -n rbac-lab -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: reader-pod-reader
subjects:
- kind: ServiceAccount
name: reader
namespace: rbac-lab
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
EOF
# Verify
kubectl auth can-i list pods \
--as=system:serviceaccount:rbac-lab:reader \
-n rbac-lab
kubectl auth can-i create pods \
--as=system:serviceaccount:rbac-lab:reader \
-n rbac-lab
# Expected: no
# Cleanup
kubectl delete namespace rbac-lab
Lab 2: Least Privilege ServiceAccount
Goal: Create a Pod with a least-privilege SA.
bash
kubectl create namespace sa-lab
# Create a ServiceAccount that can read ConfigMaps
kubectl create serviceaccount config-reader -n sa-lab
kubectl apply -n sa-lab -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: config-reader
rules:
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: config-reader
subjects:
- kind: ServiceAccount
name: config-reader
namespace: sa-lab
roleRef:
kind: Role
name: config-reader
apiGroup: rbac.authorization.k8s.io
EOF
# Create a config map
kubectl create configmap app-config --from-literal=key=value -n sa-lab
# Create a Pod using the SA
kubectl apply -n sa-lab -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: config-reader-pod
spec:
serviceAccountName: config-reader
containers:
- name: app
image: bitnami/kubectl:latest
command:
- sh
- -c
- |
# Read configmaps (allowed)
kubectl get configmaps
# Try to read secrets (should fail)
kubectl get secrets || echo "FORBIDDEN as expected"
env:
- name: KUBERNETES_SERVICE_HOST
value: "kubernetes.default.svc"
EOF
sleep 10
kubectl logs -n sa-lab config-reader-pod
# Cleanup
kubectl delete namespace sa-lab
Lab 3: Pod Security Standards
Goal: Enforce PSS and observe violations.
bash
# Create a namespace with restricted enforcement
kubectl create namespace pss-lab
kubectl label namespace pss-lab \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/warn=restricted
# Try a privileged Pod (should fail)
kubectl apply -n pss-lab -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: bad
spec:
containers:
- name: app
image: nginx
securityContext:
privileged: true
EOF
# Expected: Error from server (Forbidden)
# Try a compliant Pod
kubectl apply -n pss-lab -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: good
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: nginxinc/nginx-unprivileged:1.25-alpine
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
readOnlyRootFilesystem: false
resources:
limits:
cpu: 100m
memory: 128Mi
EOF
kubectl get pod -n pss-lab good
# Cleanup
kubectl delete namespace pss-lab
Lab 4: Kyverno Policy
Goal: Enforce non-root with Kyverno.
bash
# Install Kyverno
helm repo add kyverno https://kyverno.github.io/kyverno/
helm install kyverno kyverno/kyverno -n kyverno --create-namespace
# Wait for Kyverno
kubectl wait --for=condition=Ready pods --all -n kyverno --timeout=180s
# Create a policy
kubectl apply -f - <<'EOF'
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-non-root
spec:
validationFailureAction: Enforce
background: false
rules:
- name: check-runAsNonRoot
match:
any:
- resources:
kinds:
- Pod
validate:
message: "Pods must set runAsNonRoot: true"
pattern:
spec:
containers:
- securityContext:
runAsNonRoot: true
EOF
# Try a non-compliant Pod
kubectl run bad --image=nginx
# Expected: denied by policy
# Try a compliant Pod
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: good
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
containers:
- name: app
image: nginxinc/nginx-unprivileged:1.25-alpine
securityContext:
runAsNonRoot: true
EOF
kubectl get pod good
# Cleanup
kubectl delete pod good --ignore-not-found
kubectl delete clusterpolicy require-non-root
Lab 5: OPA Gatekeeper Constraint
Goal: Enforce required labels.
bash
# Install OPA Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml
# Wait
kubectl wait --for=condition=Ready pods -l control-plane=controller-manager -n gatekeeper-system --timeout=180s
# Create a ConstraintTemplate
kubectl apply -f - <<'EOF'
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
crd:
spec:
names:
kind: K8sRequiredLabels
validation:
openAPIV3Schema:
properties:
labels:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredlabels
violation[{"msg": msg}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.parameters.labels[_]}
missing := required - provided
count(missing) > 0
msg := sprintf("Missing labels: %v", [missing])
}
EOF
# Wait for the CRD
sleep 10
# Create a Constraint
kubectl apply -f - <<'EOF'
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-team-label
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
labels: ["team"]
EOF
# Try a Pod without label
kubectl run bad --image=nginx
# Expected: denied
# Try a Pod with label
kubectl run good --image=nginx --labels=team=platform
# Cleanup
kubectl delete pod good --ignore-not-found
kubectl delete constraint require-team-label
kubectl delete constrainttemplate k8srequiredlabels
Lab 6: Image Signature Verification
Goal: Sign an image and verify at admission.
Prerequisites: cosign, a registry (Docker Hub, ECR, or local).
bash
# Generate a key pair
cosign generate-key-pair
# Build and push an image
cat > Dockerfile <<'EOF'
FROM alpine:3.19
CMD ["echo", "hello"]
EOF
docker build -t myregistry/myapp:v1 .
docker push myregistry/myapp:v1
# Sign the image
cosign sign --key cosign.key myregistry/myapp:v1
# Verify
cosign verify --key cosign.pub myregistry/myapp:v1
# In Kyverno, create a verifyImages policy
# (uses cosign.pub content)
Kyverno policy for image verification is in the main doc.
Lab 7: RBAC Debugging
Goal: Diagnose RBAC issues.
bash
kubectl create namespace rbac-debug
# Create a ServiceAccount
kubectl create serviceaccount limited -n rbac-debug
# Check permissions
kubectl auth can-i --list --as=system:serviceaccount:rbac-debug:limited -n rbac-debug
# Should show very limited (probably nothing)
# Create a Pod running as the SA
kubectl run limited --image=bitnami/kubectl:latest -n rbac-debug \
--overrides='{"spec":{"serviceAccountName":"limited","containers":[{"name":"limited","image":"bitnami/kubectl:latest","command":["sh","-c","sleep 3600"]}]}}'
sleep 5
# Exec in and try commands
kubectl exec -n rbac-debug limited -- kubectl get pods
# Expected: Error from server (Forbidden)
# Check logs, events
kubectl describe pod limited -n rbac-debug
# Add permissions
kubectl create role pod-reader --verb=get,list,watch --resource=pods -n rbac-debug
kubectl create rolebinding limited --role=pod-reader \
--serviceaccount=rbac-debug:limited -n rbac-debug
# Retry (may need to restart pod for token refresh; projected tokens rotate)
sleep 60
kubectl exec -n rbac-debug limited -- kubectl get pods
# Expected: succeeds
# Cleanup
kubectl delete namespace rbac-debug
Lab 8: Audit Logging
Goal: Configure and read audit logs.
Note: Requires kube-apiserver access (control plane node).
bash
# Create an audit policy (on the control plane node)
sudo tee /etc/kubernetes/audit-policy.yaml <<'EOF'
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: RequestResponse
resources:
- group: ""
resources: ["secrets"]
- level: Request
resources:
- group: "rbac.authorization.k8s.io"
resources: ["roles", "clusterroles", "rolebindings", "clusterrolebindings"]
- level: Metadata
omitStages:
- RequestReceived
EOF
# Add flags to kube-apiserver (edit the static pod)
# --audit-policy-file=/etc/kubernetes/audit-policy.yaml
# --audit-log-path=/var/log/kubernetes/audit.log
# --audit-log-maxage=30
# --audit-log-maxbackup=10
# --audit-log-maxsize=100
# Restart apiserver
# (Automatic in static pod mode)
# Read audit logs
sudo tail -f /var/log/kubernetes/audit.log | jq
# Trigger an event
kubectl get secrets -n default
# Check the audit log for the secret access
sudo grep "secrets" /var/log/kubernetes/audit.log | tail -5 | jq
Lab 9: End-to-End Secure Workload
Goal: Deploy a fully hardened workload.
bash
kubectl create namespace secure-app
# Label namespace for restricted PSS
kubectl label namespace secure-app \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/warn=restricted
# ServiceAccount
kubectl create serviceaccount app-sa -n secure-app
# Role + RoleBinding (read configmaps)
kubectl apply -n secure-app -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: config-reader
rules:
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: app-config-reader
subjects:
- kind: ServiceAccount
name: app-sa
namespace: secure-app
roleRef:
kind: Role
name: config-reader
apiGroup: rbac.authorization.k8s.io
EOF
# ConfigMap
kubectl create configmap app-config --from-literal=key=value -n secure-app
# Hardened Deployment
kubectl apply -n secure-app -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: secure-app
spec:
replicas: 2
selector:
matchLabels:
app: secure-app
template:
metadata:
labels:
app: secure-app
spec:
serviceAccountName: app-sa
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: nginxinc/nginx-unprivileged:1.25-alpine
ports:
- containerPort: 8080
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
volumeMounts:
- name: cache
mountPath: /var/cache/nginx
- name: run
mountPath: /var/run
volumes:
- name: cache
emptyDir: {}
- name: run
emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
name: secure-app
spec:
selector:
app: secure-app
ports:
- port: 80
targetPort: 8080
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: secure-app
spec:
minAvailable: 1
selector:
matchLabels:
app: secure-app
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-app
spec:
podSelector:
matchLabels:
app: secure-app
policyTypes:
- Ingress
- Egress
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: ingress-nginx
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
- protocol: UDP
port: 53
EOF
# Verify
kubectl get all -n secure-app
kubectl get pdb,netpol -n secure-app
# Test
kubectl port-forward -n secure-app svc/secure-app 8080:80 &
sleep 2
curl http://localhost:8080
kill %1
# Cleanup
kubectl delete namespace secure-app
PART 7: INCIDENT MANAGEMENT
35. Security Incident Post-Mortem Template
text
INCIDENT: ServiceAccount Token Leaked - Unauthorized API Access
DATE: 2024-01-15
DURATION: 3 hours
SEVERITY: SEV-1
IMPACT: Attacker accessed production configmaps and secrets.
TIMELINE:
14:00 - Anomaly detection alert: unusual API calls from unknown IP
14:03 - Security team acknowledged
14:05 - Identified compromised ServiceAccount "backup-sa"
14:08 - Token was leaked in a public GitHub commit
14:15 - Revoked SA, recreated with new name
14:20 - Rotated all secrets the SA could access
14:30 - Audited all actions taken by the SA
16:00 - Verified no data exfiltration
17:00 - Incident closed
ROOT CAUSE:
Developer accidentally committed a ServiceAccount token to a public
GitHub repository. The token had broad permissions (list/get on
configmaps and secrets cluster-wide).
LESSONS LEARNED:
1. ServiceAccount tokens must never be committed to Git.
2. Tokens should be short-lived (projected tokens).
3. RBAC should be least-privilege (not cluster-wide).
ACTION ITEMS:
[ ] Enable Secret scanning in GitHub (Owner: Dev, Due: 2024-01-16)
[ ] Audit all ServiceAccounts for excessive permissions (Owner: Security, Due: 2024-01-20)
[ ] Enforce short-lived projected tokens (Owner: Platform, Due: 2024-01-22)
[ ] Add pre-commit hooks to prevent token commits (Owner: Dev, Due: 2024-01-25)
36. On-Call Runbook: Suspected RBAC Breach
text
SYMPTOM: Audit log alert, unexpected RBAC usage, or over-privileged identity detected.
STEP 1: Identify the compromised identity
$ kubectl get events -A | grep -i "forbidden\|unauthorized"
# Check audit logs
$ grep "system:serviceaccount:namespace:sa-name" /var/log/kubernetes/audit.log | tail -50
STEP 2: Determine blast radius
# What permissions does the identity have?
$ kubectl auth can-i --list --as=system:serviceaccount:<ns>:<sa-name>
$ kubectl get rolebindings,clusterrolebindings -A -o json | \
jq '.items[] | select(.subjects[]?.name=="<sa-name>")'
STEP 3: Isolate
# Delete the compromised SA
$ kubectl delete sa <sa-name> -n <ns>
# Or remove the RoleBinding
$ kubectl delete rolebinding <binding-name> -n <ns>
STEP 4: Check what the identity did
# Review audit logs for all actions by the SA
$ grep "<sa-name>" /var/log/kubernetes/audit.log | \
jq -r '. | "\(.timestamp) \(.verb) \(.resource.resource)/\(.resource.name) in \(.resource.namespace)"'
STEP 5: Rotate credentials
# Rotate all secrets the SA had access to
# Rotate any API keys, DB passwords, etc.
STEP 6: Fix RBAC
# Apply least-privilege
# Remove over-privileged bindings
# Add policy to prevent recurrence
STEP 7: Verify remediation
# Check that the SA is gone
# Verify no new suspicious activity
STEP 8: Escalate
# Security team, management, possibly legal
37. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | Confirmed breach / cluster-admin compromise | 5 min | Security + Platform + Management + Legal |
| SEV-2 | Suspected RBAC abuse / policy violation | 15 min | Security + Platform |
| SEV-3 | Compliance finding / misconfiguration | 1 hour | Security |
| SEV-4 | Policy warning / drift | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
38. Junior-Level Questions
| Question | Expected Answer |
| What is RBAC? | Role-Based Access Control |
| What is a ServiceAccount? | Identity for Pods |
| What is the difference between Role and ClusterRole? | Role = namespace; ClusterRole = cluster |
| What is Pod Security Standards? | Privileged, Baseline, Restricted |
| What is a webhook? | External admission callback |
39. Mid-Level Questions
| Question | Expected Answer |
| How do you debug RBAC denials? | kubectl auth can-i, describe events |
| What's the difference between Kyverno and OPA? | Kyverno = YAML, OPA = Rego |
| What is IRSA? | IAM Roles for Service Accounts (AWS) |
| What is a validating vs mutating webhook? | Mutating modifies, validating allows/denies |
| What's the failurePolicy? | Fail (reject if down) or Ignore (allow if down) |
40. Senior-Level Questions
| Question | Expected Answer |
| How do you enforce least privilege? | Scoped RBAC, non-default SA, audit |
| How do you handle over-privileged SAs? | Audit + tighten RBAC + use ValidatingAdmissionPolicy |
What's the risk of cluster-admin? | Full cluster compromise |
| How do you prevent webhook outages? | HA, failurePolicy, timeout tuning |
| How do you secure images? | Sign (cosign), verify at admission (Kyverno) |
41. Staff/Principal Questions
| Question | Expected Answer |
| Design a zero-trust Kubernetes platform. | OIDC + RBAC + PSS + NetworkPolicies + image signing + runtime detection |
| How do you handle multi-tenancy security? | Namespaces + RBAC + NetworkPolicy + Quotas + PSA |
| How do you respond to a cluster-admin compromise? | Rotate all credentials, audit, rebuild trust |
| How do you migrate from privileged to restricted PSA? | Audit → warn → enforce baseline → restricted |
| How do you enforce policy at scale? | Kyverno/OPA + CI validation + audit + gradual enforcement |
Summary Cheat Sheet
| Concept | Key Takeaway |
| Authentication | Who are you? (certs, tokens, OIDC) |
| Authorization | What can you do? (RBAC, webhooks) |
| Admission | Should we allow? (mutating → validating) |
| RBAC | Role, ClusterRole, Bindings. Additive. |
| Role | Namespace-scoped permissions |
| ClusterRole | Cluster-scoped permissions |
| RoleBinding | Bind Role or ClusterRole to subject in namespace |
| ClusterRoleBinding | Bind ClusterRole cluster-wide |
| ServiceAccount | Workload identity |
| IRSA | AWS IAM via OIDC |
| PSA | Pod Security Standards (Privileged, Baseline, Restricted) |
| PodSecurity Admission | Enforce PSS via labels |
| Mutating Webhook | Modifies resources |
| Validating Webhook | Allows/denies |
| failurePolicy | Fail or Ignore |
| Kyverno | YAML-native policy engine |
| OPA Gatekeeper | Rego policy engine |
| Image Signing | cosign sign + verify |
| External Secrets | Sync from Vault, AWS SM, etc. |
| Sealed Secrets | Encrypt in Git |
| Audit Logging | Who did what |
| NetworkPolicy | Pod firewall (default deny) |
| SecurityContext | runAsNonRoot, capabilities, seccomp |
| Encryption at rest | etcd encryption |
Stage 7: Kubernetes Networking Deep Dive — The Comprehensive Guide
PART 1: CORE THEORY
1. The Kubernetes Networking Model
Kubernetes networking is built on four fundamental rules that every Pod must satisfy.
The Four Rules
| Rule | Meaning |
| 1. Pod-to-Pod | Any Pod can reach any other Pod without NAT |
| 2. Pod-to-Service | Pods can reach Services via stable ClusterIP |
| 3. Node-to-Pod | Nodes can reach Pods without NAT |
| 4. External-to-Service | External clients reach Services via NodePort/LoadBalancer/Ingress |
The Networking Stack
text
┌─────────────────────────────────────────────────────────────┐
│ KUBERNETES NETWORKING STACK │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Pods (10.244.0.0/16) │ │
│ │ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │ Pod A │ │ Pod B │ │ │
│ │ │ 10.244.1.5 │ │ 10.244.2.8 │ │ │
│ │ └──────┬──────┘ └──────┬──────┘ │ │
│ └─────────┼────────────────┼──────────────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ CNI Plugin (Calico, Cilium, Flannel, VPC CNI) │ │
│ │ • IP assignment │ │
│ │ • veth pair creation │ │
│ │ • Cross-node routing │ │
│ │ • Network policy enforcement │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ kube-proxy (Service load balancing) │ │
│ │ • iptables / IPVS / nftables │ │
│ │ • ClusterIP → Pod IP mapping │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Node Network (eth0, VPC, underlay) │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
The Pod Network CIDR
Every cluster has a Pod CIDR (e.g., 10.244.0.0/16) from which Pod IPs are allocated. Each node gets a slice (e.g., 10.244.1.0/24).
Important: The Pod CIDR must not overlap with:
- The Node CIDR (VPC subnet)
- The Service CIDR (ClusterIP range)
- Any on-premises network you connect to
2. CNI (Container Network Interface)
CNI is the plugin interface that Kubernetes uses to configure Pod networking.
What a CNI Plugin Does
| Function | Description |
| IPAM | Assigns IP addresses to Pods |
| veth pairs | Creates virtual Ethernet pairs |
| Routing | Programs cross-node routes |
| Policy | Enforces NetworkPolicy (optional) |
The CNI Lifecycle
text
1. kubelet creates a Pod sandbox (network namespace)
2. kubelet invokes the CNI plugin with ADD command
3. CNI plugin:
a. Allocates an IP from the Pod CIDR
b. Creates a veth pair (one end in Pod, one on host)
c. Configures routes so the Pod can reach other Pods
d. Returns the IP to kubelet
4. kubelet starts the container in the sandbox
CNI Plugin Categories
| Category | Examples | Approach |
| Overlay | Flannel (VXLAN) | Encapsulates pod traffic |
| Routing | Calico (BGP) | Programs routes natively |
| eBPF | Cilium | Kernel-level networking |
| Cloud-native | AWS VPC CNI, Azure CNI | Uses cloud VPC IPs |
| Simple | Bridge, host-local | Basic connectivity |
CNI Requirements
| Requirement | Why |
| Pod CIDR | IP allocation range |
| Kernel modules | VXLAN, eBPF, etc. |
| Node permissions | Network namespace access |
| CNI config | /etc/cni/net.d/ |
3. Service Networking
A Service provides a stable virtual IP (ClusterIP) that load-balances to a set of Pods.
The Four Service Types
| Type | Accessibility | Use Case |
| ClusterIP | Internal only | Service-to-service |
| NodePort | Via Node IP + port | Development, on-prem |
| LoadBalancer | Cloud LB | Production external |
| ExternalName | DNS alias | External services |
ClusterIP (Default)
yaml
apiVersion: v1
kind: Service
metadata:
name: web
spec:
type: ClusterIP
selector:
app: web
ports:
- port: 80
targetPort: 8080
port: Service port (what clients connect to)targetPort: Pod port (where traffic is forwarded)
ClusterIP range: Typically 10.96.0.0/12 (configurable).
NodePort
yaml
spec:
type: NodePort
ports:
- port: 80
targetPort: 8080
nodePort: 30080
Range: 30000–32767 (default).
Access: <NodeIP>:30080.
LoadBalancer
yaml
spec:
type: LoadBalancer
ports:
- port: 80
targetPort: 8080
Provisions a cloud LB (AWS ELB/ALB/NLB, GCP LB, Azure LB).
ExternalName
yaml
spec:
type: ExternalName
externalName: db.example.com
DNS-only CNAME. No proxying.
How Service Load Balancing Works
text
Client → ClusterIP (10.96.0.10) → kube-proxy → Pod IP (10.244.1.5)
│
├── iptables DNAT
├── IPVS virtual server
└── eBPF map lookup
Service DNS
Every Service gets a DNS name:
text
<service>.<namespace>.svc.cluster.local
Examples:
web.default.svc.cluster.local(FQDN)web.default(same cluster)web(same namespace)
Endpoints and EndpointSlices
The Service's backing Pods are tracked in EndpointSlice objects.
bash
kubectl get endpoints web
kubectl get endpointslices -l kubernetes.io/service-name=web
Empty endpoints = no Pods match the selector. This is the #1 cause of Service failures.
4. kube-proxy
kube-proxy is the component that implements Service load balancing on each node.
kube-proxy Modes
| Mode | Mechanism | Scalability |
| iptables | iptables DNAT rules | Poor (linear with services) |
| IPVS | IPVS virtual servers | Good (hash-based) |
| nftables | nftables rules | Modern (replaces iptables) |
iptables Mode
Every Service creates iptables rules. As services grow, rules grow linearly:
text
10 services: 100 rules
100 services: 1,000 rules
1,000 services: 10,000 rules
Problem: Every packet traverses the chain. Performance degrades.
IPVS Mode
IPVS uses hash tables with O(1) lookup. Performance is stable regardless of service count.
IPVS advantages:
- Multiple load-balancing algorithms (round-robin, least connections, etc.)
- Better scalability
- Server health checking
- Connection retries
Performance difference: The main difference between IPVS and iptables is in TCP connection establishment. For short connections, IPVS is significantly faster. As Service and Endpoint counts increase, iptables performance drops while IPVS remains stable.
nftables Mode
nftables is the modern replacement for iptables. It's more efficient and has a cleaner syntax.
Kubernetes 1.31+ supports nftables mode in kube-proxy.
kube-proxy Components
| Component | Purpose |
| Service watcher | Watches Service/Endpoint changes |
| Rule programmer | Writes iptables/IPVS rules |
| Health checker | (IPVS only) Probes backend health |
| Metrics exporter | Exposes Prometheus metrics |
The kube-proxy Performance Problem
Even IPVS requires netfilter hooks and conntrack overhead. At high scale, this causes:
- CPU overhead from packet processing
- conntrack table pressure
- The UDP conntrack race condition (5-second DNS timeout)
Solution: eBPF-based kube-proxy replacement (Cilium).
5. CoreDNS
CoreDNS is the cluster DNS server. Every Pod's /etc/resolv.conf points to the CoreDNS ClusterIP.
How CoreDNS Works
text
Pod → /etc/resolv.conf (nameserver 10.96.0.10)
│
▼
CoreDNS (kube-dns Service)
│
├── For cluster.local → returns Service/Endpoint IPs
├── For external domains → forwards to upstream DNS
└── Caches responses
CoreDNS Configuration
Stored in the coredns ConfigMap in kube-system:
text
.:53 {
errors
health
ready
kubernetes cluster.local in-addr.arpa ip6.arpa {
pods insecure
fallthrough in-addr.arpa ip6.arpa
ttl 30
}
prometheus :9153
forward . /etc/resolv.conf
cache 30
loop
reload
loadbalance
}
Key CoreDNS Plugins
| Plugin | Purpose |
| kubernetes | Serves cluster.local records |
| forward | Forwards external queries |
| cache | Caches responses |
| health | Health endpoint |
| prometheus | Metrics |
| loop | Detects forwarding loops |
| reload | Auto-reload config |
Pod DNS Configuration
text
nameserver 10.96.0.10
search default.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
The ndots:5 problem: Any name with fewer than 5 dots triggers search-domain expansion.
For api.stripe.com (2 dots < 5):
api.stripe.com.default.svc.cluster.local→ NXDOMAINapi.stripe.com.svc.cluster.local→ NXDOMAINapi.stripe.com.cluster.local→ NXDOMAINapi.stripe.com.→ Success
One logical lookup = 4 wire queries.
NodeLocal DNSCache
NodeLocal DNSCache runs a DNS cache on every node as a DaemonSet.
| Benefit | Explanation |
| Bypasses conntrack | UDP → TCP conversion |
| Eliminates 5s timeout | No UDP conntrack race |
| Sub-ms cache hits | Never leaves the node |
| Reduces CoreDNS load | 80–95% fewer queries |
Architecture:
text
Pod → 169.254.20.10 (NodeLocal DNSCache) → TCP → CoreDNS
│
└── Cache hit: answer locally
└── Cache miss: forward to CoreDNS over TCP
PART 2: ADVANCED CONCEPTS
6. CNI Deep Dive
Flannel (Simple Overlay)
| Aspect | Details |
| Approach | VXLAN overlay |
| Policy | ❌ None |
| Performance | Good, but encapsulation overhead |
| Use Case | K3s default, simple clusters |
Flannel's design philosophy is "do one thing well." A user-space daemon manages subnet allocation, while the kernel's VXLAN and bridge code handles forwarding. No policy, no observability — just connectivity.
Calico (Policy Powerhouse)
| Aspect | Details |
| Approach | BGP routing, iptables/eBPF |
| Policy | ✅ Excellent NetworkPolicy |
| Performance | Excellent (no encapsulation by default) |
| Use Case | Production, policy-heavy |
Calico supports multiple data planes — iptables, nftables, eBPF, Windows HNS, and VPP — allowing operators to choose the best fit. The control plane includes Felix (per-node agent) and BIRD (BGP daemon).
Cilium (eBPF Native)
| Aspect | Details |
| Approach | eBPF (kernel-native) |
| Policy | ✅ L3/L4/L7 |
| Performance | Best (O(1) lookups) |
| Use Case | Modern, high-performance |
Cilium was purpose-built around eBPF. Every packet passes through eBPF programs attached to network interfaces. The architecture consists of:
- Cilium Agent — DaemonSet per node, translates policies into eBPF programs
- Cilium Operator — Cluster-wide IPAM, garbage collection
- Hubble — Built-in observability from eBPF data paths
Cilium's policy model is identity-based rather than IP-based. Pods are assigned cryptographic identities derived from Kubernetes labels, service accounts, and namespaces. Policies survive pod rescheduling and IP changes.
AWS VPC CNI
| Aspect | Details |
| Approach | Native VPC IPs |
| Policy | ✅ (via Calico) |
| Performance | Excellent (native VPC) |
| Use Case | AWS EKS |
The Amazon VPC CNI assigns pods real VPC IP addresses, enabling native VPC networking. Security groups, NACLs, and flow logs all work natively.
Two components:
- CNI binary — invoked by kubelet on pod add/remove
- ipamd (aws-node DaemonSet) — manages ENIs and maintains a warm pool of IPs
Modes:
| Mode | IP Usage | Pod Density |
| Secondary IP (default) | 1 IP per pod | Limited by ENI × IPs |
| Prefix Delegation | /28 prefix per ENI slot | ~4-16× more pods |
| Custom Networking | Different subnet for pods | Separate CIDR |
Prefix Delegation assigns /28 prefixes (16 IPs each) to ENI slots, dramatically increasing pod density. With prefix mode, an m5.large can support 110 pods vs 29 in secondary IP mode.
CNI Comparison Table
| CNI | Approach | Policy | Performance | Best For |
| Flannel | VXLAN overlay | ❌ | Good | Simple clusters |
| Calico | BGP, iptables/eBPF | ✅ Full | Excellent | Policy-heavy |
| Cilium | eBPF | ✅ L3/L4/L7 | Best | Modern, high-performance |
| AWS VPC CNI | Native VPC | ✅ (via Calico) | Excellent | EKS |
| Azure CNI | Native VNET | ✅ | Excellent | AKS |
| GKE Dataplane V2 | Cilium-based | ✅ | Best | GKE |
7. Cilium and eBPF
Why eBPF Changes Everything
Traditional networking (iptables) uses linear rule chains. eBPF uses hash tables with O(1) lookups. The time to resolve a service is constant regardless of whether you have 10 or 10,000 services.
Cilium Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ CILIUM ARCHITECTURE │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Cilium Agent (DaemonSet) │ │
│ │ • Watches K8s API for Pods, Services, Policies │ │
│ │ • Compiles policies into eBPF programs │ │
│ │ • Loads programs into kernel │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ eBPF Programs (attached to veth interfaces) │ │
│ │ • Process packets at TC/XDP hooks │ │
│ │ • O(1) map lookups │ │
│ │ • Identity-based policies │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Hubble (Observability) │ │
│ │ • Real-time flow visibility │ │
│ │ • DNS query logging │ │
│ │ • L7 protocol inspection │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Cilium vs Calico Performance
Benchmarks show Cilium delivers approximately 25% higher throughput in service routing scenarios.
| Metric | Cilium (eBPF) | Calico (iptables) |
| Service routing | O(1) | O(n) |
| Throughput | 25% higher | Baseline |
| CPU at scale | Stable | Increases |
| Latency | Lower | Higher |
Cilium Features
| Feature | Description |
| kube-proxy replacement | eBPF service load balancing |
| L7 policies | HTTP, gRPC, Kafka |
| Hubble | Flow-level observability |
| Cluster Mesh | Multi-cluster networking |
| Service Mesh | Sidecarless mesh |
| Runtime security | Tetragon |
Kernel Requirements
Cilium requires Linux kernel 4.19.57 or newer for full eBPF functionality. Modern managed Kubernetes (GKE, AKS, EKS) all meet this requirement.
8. kube-proxy Replacement with eBPF
Why Replace kube-proxy
Traditional kube-proxy modes have scaling issues:
- iptables: Every packet traverses a chain that grows with service count
- IPVS: Improves with hash tables but still requires netfilter hooks and conntrack overhead
How eBPF Replacement Works
eBPF-based implementations attach directly to network interfaces and cgroups, processing service traffic before the normal kube-proxy datapath. Service lookups use eBPF maps with O(1) complexity. Connection tracking happens in eBPF maps rather than iptables state.
Installing Cilium with kube-proxy Replacement
bash
# Initialize without kube-proxy
kubeadm init --skip-phases=addon/kube-proxy \
--pod-network-cidr=10.244.0.0/16
# Install Cilium
helm repo add cilium https://helm.cilium.io/
helm install cilium cilium/cilium \
--namespace kube-system \
--set kubeProxyReplacement=true \
--set k8sServiceHost=API_SERVER_IP \
--set k8sServicePort=API_SERVER_PORT \
--set bpf.masquerade=true \
--set ipam.mode=kubernetes
Verifying the Replacement
bash
# Check Cilium status
kubectl -n kube-system exec ds/cilium -- cilium-dbg status | grep KubeProxyReplacement
# Should show: KubeProxyReplacement: True
# Verify no kube-proxy pods
kubectl get pods -n kube-system -l k8s-app=kube-proxy
# Should return no resources
Benefits of eBPF Replacement
| Benefit | Description |
| O(1) service lookup | Constant regardless of service count |
| No conntrack race | Eliminates UDP DNS timeout |
| DSR support | Direct Server Return |
| Maglev hashing | Better load distribution |
| Session affinity without conntrack | Simpler, faster |
| Faster failover | Endpoint changes propagate faster |
9. NetworkPolicy
NetworkPolicy is the Kubernetes firewall for Pods.
Default Behavior
By default, all Pods can talk to all Pods. This is a security risk.
The Default Deny Pattern
The core best practice is to default-deny all traffic and then explicitly allow only what each workload needs. Apply default-deny for both ingress and egress in each namespace.
Default Deny All
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
Empty podSelector: {} = all Pods in the namespace.
Allow Specific Ingress
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: production
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
Allow Specific Egress
yaml
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Egress
egress:
- to:
- namespaceSelector:
matchLabels:
name: kube-system
ports:
- protocol: UDP
port: 53
NetworkPolicy Best Practices
| Practice | Why |
| Start with default deny per namespace | Foundation of zero-trust |
| Label everything consistently | Policies rely on selectors |
| Test in monitor mode first | Avoid breaking traffic |
| Enforce both ingress and egress | Egress prevents exfiltration |
| Review effective policy regularly | Detect drift |
| Never flip the whole cluster at once | Roll out per namespace |
NetworkPolicy Limitations
Native NetworkPolicies operate at L3/L4. They cannot:
- Filter by HTTP path or method
- Match DNS names
- Inspect gRPC methods
- See application-layer data
For L7 policies, you need Cilium NetworkPolicy.
10. Cilium NetworkPolicy (L7 Policies)
CiliumNetworkPolicy extends NetworkPolicy with L7 (application layer) rules.
L7 HTTP Policy
yaml
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: allow-http-get
spec:
endpointSelector:
matchLabels:
app: backend
ingress:
- fromEndpoints:
- matchLabels:
app: frontend
toPorts:
- ports:
- port: "8080"
protocol: TCP
rules:
http:
- method: "GET"
path: "/api/.*"
This allows only GET requests to /api/*.
gRPC Policy
Cilium treats gRPC as HTTP/2 traffic. Each gRPC method maps to an HTTP POST path such as /package.Service/Method. Cilium's HTTP L7 policy engine can match and filter gRPC calls using path regex, enabling method-level access control.
yaml
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: allow-grpc-method
spec:
endpointSelector:
matchLabels:
app: grpc-server
ingress:
- fromEndpoints:
- matchLabels:
app: grpc-client
toPorts:
- ports:
- port: "50051"
protocol: TCP
rules:
http:
- method: "POST"
path: "/helloworld.Greeter/SayHello"
When to Use L7 Policies
| Scenario | L7 Policy |
| API gateway restrictions | ✅ Yes |
| gRPC method-level access | ✅ Yes |
| Kafka topic restrictions | ✅ Yes |
| Simple L3/L4 isolation | ❌ Use native NetworkPolicy |
| High-throughput traffic | ⚠️ L7 has performance cost |
Performance note: Benchmarks show eBPF-based Cilium maintains 8.9K Mbps under complex L3/L4 policies, but drops to 94 Mbps with L7 processing. Use L7 policies selectively.
11. Ingress Controllers
An Ingress Controller implements Ingress resources — HTTP/HTTPS routing into the cluster.
Why Ingress Controllers
| Without Ingress | With Ingress |
| One LoadBalancer per app (expensive) | One external IP, many routes |
| No path-based routing | Path and host-based routing |
| No TLS termination | Centralized TLS |
Ingress Controller Comparison
| Controller | Performance | Auto TLS | gRPC | TCP/UDP |
| NGINX Ingress | ~20K RPS | cert-manager | ✅ | ✅ |
| Traefik | ~19K RPS | Built-in | ✅ | ✅ |
| HAProxy Ingress | ~100K+ RPS | cert-manager | ✅ | ✅ |
| Envoy | ~18.5K RPS | cert-manager | ✅ | ✅ |
HAProxy Ingress is the performance leader, documented at over 100K requests/second per replica with tuning.
NGINX Ingress (Most Popular)
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
tls:
- hosts:
- app.example.com
secretName: tls-secret
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
Traefik (Built-in TLS)
Traefik has built-in Let's Encrypt support, eliminating the need for cert-manager.
yaml
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: web
spec:
entryPoints:
- websecure
routes:
- match: Host(`app.example.com`)
kind: Rule
services:
- name: web
port: 80
tls:
certResolver: letsencrypt
HAProxy Ingress (Performance Leader)
HAProxy is the performance leader for TCP/UDP load balancing scenarios.
Ingress Class
yaml
spec:
ingressClassName: nginx
If multiple Ingress controllers exist, ingressClassName selects which one handles the Ingress.
Common Ingress Annotations
| Annotation | Purpose |
nginx.ingress.kubernetes.io/rewrite-target | Rewrite path |
nginx.ingress.kubernetes.io/ssl-redirect | Force HTTPS |
nginx.ingress.kubernetes.io/proxy-body-size | Max upload |
nginx.ingress.kubernetes.io/rate-limit | Rate limiting |
cert-manager.io/cluster-issuer | Auto TLS |
12. Gateway API
The Gateway API is the official successor to Ingress.
Why Gateway API
Ingress limitations:
- Annotation overload — Advanced features require controller-specific annotations that are not portable.
- No role separation — The same resource defines infrastructure and application routing.
- Limited protocol support — Only HTTP/HTTPS. No TCP, UDP, or gRPC-native routing.
- No header-based routing — Cannot route based on headers without annotations.
- No traffic splitting — Canary deployments require non-standard annotations.
Gateway API Resources
| Resource | Owner | Purpose |
| GatewayClass | Infrastructure | Defines the controller |
| Gateway | Infrastructure | Listener configuration |
| HTTPRoute | Application | HTTP routing rules |
| GRPCRoute | Application | gRPC routing |
| TLSRoute | Application | TLS passthrough |
| ReferenceGrant | Application | Cross-namespace refs |
Gateway API Example
Infrastructure team creates the Gateway:
yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: main-gateway
namespace: gateway-system
spec:
gatewayClassName: istio
listeners:
- name: http
protocol: HTTP
port: 80
allowedRoutes:
namespaces:
from: All
- name: https
protocol: HTTPS
port: 443
tls:
mode: Terminate
certificateRefs:
- name: wildcard-tls
Application team creates routes:
yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: app-routes
namespace: default
spec:
parentRefs:
- name: main-gateway
namespace: gateway-system
rules:
- matches:
- path:
type: PathPrefix
value: /api
backendRefs:
- name: api-service
port: 80
Gateway API Status (2026)
As of 2026, core Gateway API resources — GatewayClass, Gateway, HTTPRoute, GRPCRoute, TLSRoute, and ReferenceGrant — have reached GA (General Availability) and are production-ready. Some route types (TCPRoute, UDPRoute) are still experimental.
13. Ingress vs Gateway API
The Retirement of Ingress NGINX
Ingress NGINX maintenance ends in March 2026. This gives infrastructure teams a deadline and an opportunity to re-evaluate their ingress strategy.
Comparison Table
| Aspect | Ingress | Gateway API |
| Status | Stable (maintenance mode) | GA (recommended) |
| Role separation | ❌ No | ✅ Yes |
| Protocol support | HTTP/HTTPS | HTTP, HTTPS, gRPC, TCP, UDP |
| Header routing | Annotations only | ✅ Native |
| Traffic splitting | Annotations only | ✅ Native |
| Cross-namespace | Limited | ✅ ReferenceGrant |
| Portability | Controller-specific | ✅ Standard |
Migration Guide
Step 1: Deploy a Gateway API controller
Options: Istio, Cilium, Envoy Gateway, NGINX Gateway Fabric, Kong, Traefik.
Step 2: Create GatewayClass and Gateway
yaml
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: my-gateway-class
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: my-gateway
spec:
gatewayClassName: my-gateway-class
listeners:
- name: http
protocol: HTTP
port: 80
Step 3: Create HTTPRoutes (migrate from Ingress)
Step 4: Test, then remove Ingress resources
Migration Strategy
| Phase | Action |
| 1. Pilot | Deploy Gateway API for one service |
| 2. Validate | Test routing, TLS, observability |
| 3. Expand | Migrate more services |
| 4. Retire | Remove Ingress resources |
Gateway API is recommended over Ingress for new clusters as of 2026.
14. DNS in Kubernetes
The ndots:5 Problem
Every Pod gets:
text
options ndots:5
Impact: Names with fewer than 5 dots trigger search-domain expansion.
For api.stripe.com:
- Query 1:
api.stripe.com.default.svc.cluster.local - Query 2:
api.stripe.com.svc.cluster.local - Query 3:
api.stripe.com.cluster.local - Query 4:
api.stripe.com.
4 queries for 1 logical lookup.
Fixes
Option 1: Use trailing dots
bash
curl http://api.stripe.com.
The trailing dot means "absolute name" — no search domain expansion.
Option 2: Lower ndots
yaml
spec:
dnsConfig:
options:
- name: ndots
value: "2"
Now api.stripe.com (2 dots) is treated as absolute.
The 5-Second DNS Timeout
Problem: Parallel A and AAAA UDP queries from the same socket hit the conntrack race condition in the Linux kernel. One packet is dropped. The resolver waits for its 5-second timeout.
Solution: NodeLocal DNSCache.
NodeLocal DNSCache improves cluster DNS performance and resolves the DNAT conntrack contention issue by running a DaemonSet-based DNS caching proxy on cluster nodes.
How it works:
| Step | What Happens |
| 1 | Pod queries 169.254.20.10 (local link) |
| 2 | NodeLocal DNSCache receives UDP |
| 3 | Cache hit → answer locally (sub-ms) |
| 4 | Cache miss → forward over TCP to CoreDNS |
| 5 | TCP conntrack entries are short-lived |
Result: Eliminates the 5-second timeout.
CoreDNS Metrics to Monitor
| Metric | What It Shows |
coredns_dns_requests_total | Total queries |
coredns_dns_responses_total | Responses by rcode |
coredns_cache_hits_total | Cache hits |
coredns_forward_requests_total | Upstream queries |
coredns_dns_request_duration_seconds | Query latency |
15. Headless Services
A Headless Service (clusterIP: None) returns Pod IPs directly instead of a ClusterIP.
How Headless Works
| Aspect | Normal Service | Headless Service |
| ClusterIP | Virtual IP | None |
| DNS returns | ClusterIP | All Pod IPs |
| Load balancing | kube-proxy | Client-side |
| Use case | Stateless | StatefulSets |
Headless Service Example
yaml
apiVersion: v1
kind: Service
metadata:
name: db-headless
spec:
clusterIP: None
selector:
app: postgres
ports:
- port: 5432
DNS for Headless
text
db-headless.default.svc.cluster.local → 10.244.1.5, 10.244.2.8, 10.244.3.2
Each Pod also gets its own DNS:
text
postgres-0.db-headless.default.svc.cluster.local
postgres-1.db-headless.default.svc.cluster.local
postgres-2.db-headless.default.svc.cluster.local
Use Cases
| Use Case | Why Headless |
| StatefulSets | Stable identity per Pod |
| Databases | Clients connect to specific replicas |
| Message queues | Brokers need stable IDs |
| Peer discovery | Pods find each other directly |
16. Multi-Cluster Networking
Cluster Mesh (Cilium)
Cilium's Cluster Mesh connects multiple Kubernetes clusters with:
- Cross-cluster service discovery
- Global load balancing
- Unified network policy
- Cross-cluster pod-to-pod communication
Submariner
Submariner connects clusters across clouds and on-premises. It uses a gateway node in each cluster to establish tunnels.
Multi-Cluster Service Discovery
| Approach | Tool |
| Cluster Mesh | Cilium |
| Submariner | Open source |
| Service Mirroring | Admiralty |
| DNS-based | CoreDNS federation |
PART 3: PRODUCTION FAILURE MODES
17. Top 10 Kubernetes Networking Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | Service has no endpoints | Connection refused | Selector mismatch | Fix labels |
| 2 | DNS resolution fails | "Name not resolved" | CoreDNS down, ndots | Check CoreDNS, NodeLocal |
| 3 | 5-second DNS timeout | Intermittent 5s stalls | conntrack race | NodeLocal DNSCache |
| 4 | CNI pod not ready | Pods stuck Pending | CNI daemonset down | Check CNI logs |
| 5 | NetworkPolicy blocks traffic | Connection timeout | Overly strict policy | Test with allow-all |
| 6 | IP exhaustion | Pods can't get IPs | Pod CIDR exhausted | Expand CIDR, prefix delegation |
| 7 | Ingress 502 errors | Bad Gateway | Backend not ready | Check endpoints |
| 8 | Cross-node traffic fails | Pods can't reach each other | Routing issue | Check CNI, node routes |
| 9 | kube-proxy stale rules | Service unreachable | Rule programming lag | Restart kube-proxy |
| 10 | Gateway API misconfiguration | 404 errors | Wrong parentRefs | Check Gateway/Route |
18. Networking Debugging Runbook
"Service is Unreachable" — Step-by-Step
text
STEP 1: Check the Service
$ kubectl get svc <service> -o yaml
# Verify selector, port, targetPort
STEP 2: Check endpoints
$ kubectl get endpoints <service>
$ kubectl get endpointslices -l kubernetes.io/service-name=<service>
# Empty endpoints = selector mismatch
STEP 3: Check Pods match selector
$ kubectl get pods -l <selector>
# If no pods, fix labels
STEP 4: Check Pod readiness
$ kubectl get pods -l <selector>
# If not Ready, check readiness probes
STEP 5: Test from inside cluster
$ kubectl run test --image=busybox --rm -it --restart=Never -- \
wget -qO- <service>:<port>
STEP 6: Check DNS
$ kubectl run test --image=busybox --rm -it --restart=Never -- \
nslookup <service>
STEP 7: Check NetworkPolicy
$ kubectl get networkpolicies -A
# Look for default-deny or restricting policies
STEP 8: 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
STEP 9: Check CNI
$ kubectl get pods -n kube-system -l k8s-app=cilium
$ kubectl logs -n kube-system -l k8s-app=cilium --tail=50
STEP 10: Escalate
Quick Diagnostic Table
| Symptom | First Check | Then |
| No endpoints | kubectl get endpoints | Fix selector |
| DNS fails | CoreDNS pods | NodeLocal DNSCache |
| 502/503 | Backend readiness | Ingress logs |
| Timeout | NetworkPolicy | CNI logs |
| Cross-node fail | Node routes | CNI routing |
19. Blast Radius Analysis
What Happens When Networking Fails?
| Component | Impact | Severity |
| CNI down | All new Pods can't network | SEV-1 |
| CoreDNS down | Service discovery fails | SEV-1 |
| kube-proxy down | Services unreachable | SEV-1 |
| Ingress down | External access fails | SEV-1 |
| NetworkPolicy misconfig | Traffic blocked | SEV-2 |
| IP exhaustion | Pods stuck Pending | SEV-1 |
| 5s DNS timeout | Intermittent latency | SEV-2 |
Mitigation Strategies
| Strategy | Implementation |
| HA CoreDNS | 3+ replicas, PDB |
| NodeLocal DNSCache | Eliminates conntrack race |
| HA Ingress | 3+ replicas, anti-affinity |
| CNI HA | DaemonSet on every node |
| IP capacity planning | Monitor CIDR utilization |
| NetworkPolicy testing | Audit before enforce |
PART 4: CAPACITY PLANNING & COST MODELING
20. CNI Performance and Overhead Modeling
CNI Overhead by Type
| CNI | CPU per Node | Memory per Node | Throughput |
| Flannel | Low | Low | Good |
| Calico (iptables) | Medium | Medium | Excellent |
| Calico (eBPF) | Low | Medium | Excellent |
| Cilium | Low | Medium | Best |
| AWS VPC CNI | Low | Medium | Excellent |
Pod IP Capacity
| Mode | m5.large | m5.xlarge | m5.4xlarge |
| Secondary IP | 29 | 58 | 234 |
| Prefix Delegation | 110 | 220 | 880 |
CNI Selection Criteria
| Factor | Weight |
| Performance | High |
| Policy features | High |
| Observability | Medium |
| Operational complexity | Medium |
| Cloud integration | High |
21. Ingress Controller Capacity Planning
Throughput per Replica
| Controller | RPS per Replica | CPU per 10K RPS |
| NGINX | 20,000 | 2 cores |
| Traefik | 19,000 | 2 cores |
| HAProxy | 100,000+ | 2 cores |
| Envoy | 18,500 | 2 cores |
Sizing Formula
text
Replicas = (Peak RPS / RPS per replica) × 1.5 (headroom)
Example: 200,000 peak RPS with NGINX
Replicas = (200,000 / 20,000) × 1.5 = 15 replicas
22. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Networking SLA Design
| Target | Architecture |
| 99.9% | Basic CNI, CoreDNS 2 replicas |
| 99.99% | HA CNI, NodeLocal DNSCache, HA Ingress |
| 99.999% | Cilium, kube-proxy replacement, multi-cluster |
PART 5: ARCHITECTURE & STRATEGY
23. Zero-Trust Networking Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ ZERO-TRUST NETWORKING │
│ │
│ Layer 1: Default Deny │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ NetworkPolicy: default-deny all namespaces │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 2: Explicit Allow │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ NetworkPolicy: allow only required traffic │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 3: L7 Policy │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ CiliumNetworkPolicy: HTTP methods, gRPC paths │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 4: mTLS │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Service Mesh: Istio/Linkerd/Cilium │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 5: Observability │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Hubble: flow-level visibility │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
24. CNI Selection Framework
| Requirement | Recommended CNI |
| New cluster (2026) | Cilium |
| Policy-heavy, existing | Calico |
| AWS EKS | AWS VPC CNI (+ Calico for policy) |
| Azure AKS | Azure CNI |
| GKE | Dataplane V2 (Cilium-based) |
| Simple, K3s | Flannel |
| eBPF, no kube-proxy | Cilium |
Recommendation for 2026: Cilium for new clusters (eBPF performance, L7 visibility).
25. Compliance & Security for Networking
| Framework | Networking Requirement |
| PCI-DSS | Network segmentation, default deny |
| HIPAA | Encryption in transit, audit |
| SOC2 | Change management, monitoring |
| GDPR | Data residency |
| FedRAMP | FIPS 140-2, default deny |
PART 6: HANDS-ON LABS
Lab 1: Explore CNI and Pod Networking
Goal: Understand CNI and Pod networking.
bash
# Check CNI plugin
kubectl get pods -n kube-system | grep -E "cilium|calico|flannel"
# Check Pod CIDR
kubectl get nodes -o jsonpath='{.items[*].spec.podCIDR}'
# Create two Pods
kubectl run pod-a --image=busybox --restart=Never -- sleep 3600
kubectl run pod-b --image=busybox --restart=Never -- sleep 3600
# Get their IPs
kubectl get pods -o wide
# Test pod-to-pod connectivity
POD_A_IP=$(kubectl get pod pod-a -o jsonpath='{.status.podIP}')
kubectl exec pod-b -- ping -c 2 $POD_A_IP
# Cleanup
kubectl delete pod pod-a pod-b
Lab 2: Master Service Types
Goal: Practice all Service types.
bash
# Create a Deployment
kubectl create deployment web --image=nginx:1.25-alpine --replicas=3
# ClusterIP
kubectl expose deployment web --port=80 --target-port=80 --name=web-clusterip
kubectl run test --image=busybox --rm -it --restart=Never -- wget -qO- web-clusterip
# NodePort
kubectl expose deployment web --port=80 --target-port=80 --type=NodePort --name=web-nodeport
kubectl get svc web-nodeport
# LoadBalancer
kubectl expose deployment web --port=80 --target-port=80 --type=LoadBalancer --name=web-lb
kubectl get svc web-lb
# Cleanup
kubectl delete svc web-clusterip web-nodeport web-lb
kubectl delete deployment web
Lab 3: Configure CoreDNS and NodeLocal DNSCache
Goal: Deploy NodeLocal DNSCache.
bash
# Check CoreDNS
kubectl get pods -n kube-system -l k8s-app=kube-dns
kubectl get configmap coredns -n kube-system -o yaml
# Deploy NodeLocal DNSCache
wget https://raw.githubusercontent.com/kubernetes/kubernetes/master/cluster/addons/dns/nodelocaldns/nodelocaldns.yaml
sed -i 's/__PILLAR__DNS__SERVER__/10.96.0.10/g' nodelocaldns.yaml
sed -i 's/__PILLAR__DNS__DOMAIN__/cluster.local/g' nodelocaldns.yaml
kubectl apply -f nodelocaldns.yaml
# Verify
kubectl get pods -n kube-system -l k8s-app=node-local-dns
# Test
kubectl run test --image=busybox --rm -it --restart=Never -- \
nslookup kubernetes.default
Lab 4: Implement NetworkPolicy
Goal: Default deny + explicit allow.
bash
kubectl create namespace netpol-lab
# Create frontend and backend
kubectl create deployment frontend --image=nginx -n netpol-lab
kubectl create deployment backend --image=nginx -n netpol-lab
kubectl expose deployment backend --port=80 -n netpol-lab
# Test connectivity (should work — no policies yet)
kubectl run test -n netpol-lab --image=busybox --rm -it --restart=Never -- \
wget -qO- backend
# Apply default deny
kubectl apply -n netpol-lab -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
EOF
# Test (should fail)
kubectl run test -n netpol-lab --image=busybox --rm -it --restart=Never -- \
wget -qO- backend
# Allow frontend → backend
kubectl apply -n netpol-lab -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
spec:
podSelector:
matchLabels:
app: backend
policyTypes: [Ingress]
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 80
EOF
# Test from a frontend pod
FRONTEND_POD=$(kubectl get pods -n netpol-lab -l app=frontend -o jsonpath='{.items[0].metadata.name}')
kubectl exec -n netpol-lab $FRONTEND_POD -- wget -qO- backend
# Cleanup
kubectl delete namespace netpol-lab
Lab 5: Cilium L7 NetworkPolicy
Goal: Apply HTTP method-level policy.
Prerequisites: Cilium installed.
bash
# Deploy an HTTP server
kubectl create deployment httpbin --image=kennethreitz/httpbin
kubectl expose deployment httpbin --port=80
# L7 policy: allow only GET /get
kubectl apply -f - <<'EOF'
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: allow-get-only
spec:
endpointSelector:
matchLabels:
app: httpbin
ingress:
- fromEndpoints:
- matchLabels:
app: client
toPorts:
- ports:
- port: "80"
protocol: TCP
rules:
http:
- method: "GET"
path: "/get"
EOF
# Test
kubectl run client --image=busybox --labels=app=client --restart=Never -- sleep 3600
kubectl exec client -- wget -qO- httpbin/get # Should work
kubectl exec client -- wget -qO- httpbin/post # Should fail
# Cleanup
kubectl delete pod client --ignore-not-found
kubectl delete deployment httpbin
kubectl delete svc httpbin
kubectl delete ciliumnetworkpolicy allow-get-only
Lab 6: Deploy and Configure an Ingress Controller
Goal: Deploy NGINX Ingress and route traffic.
bash
# Deploy NGINX Ingress
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/cloud/deploy.yaml
# Wait for it
kubectl wait --namespace ingress-nginx \
--for=condition=ready pod \
--selector=app.kubernetes.io/component=controller \
--timeout=180s
# Create an app
kubectl create deployment web --image=nginx:1.25-alpine
kubectl expose deployment web --port=80
# Create Ingress
kubectl apply -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
spec:
ingressClassName: nginx
rules:
- host: app.local
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
EOF
# Test (with port-forward or /etc/hosts)
kubectl get ingress
kubectl port-forward -n ingress-nginx svc/ingress-nginx-controller 8080:80 &
sleep 2
curl -H "Host: app.local" http://localhost:8080
kill %1
# Cleanup
kubectl delete ingress web-ingress
kubectl delete svc web
kubectl delete deployment web
Lab 7: Migrate from Ingress to Gateway API
Goal: Convert Ingress to HTTPRoute.
Prerequisites: Gateway API CRDs installed.
bash
# Install Gateway API CRDs
kubectl apply -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.0.0/standard-install.yaml
# Create a GatewayClass
kubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: my-gateway-class
spec:
controllerName: example.com/gateway-controller
EOF
# Create a Gateway
kubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: my-gateway
spec:
gatewayClassName: my-gateway-class
listeners:
- name: http
protocol: HTTP
port: 80
EOF
# Create an HTTPRoute
kubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: app-route
spec:
parentRefs:
- name: my-gateway
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: web
port: 80
EOF
# Check
kubectl get gateways,httproutes
# Cleanup
kubectl delete httproute app-route
kubectl delete gateway my-gateway
kubectl delete gatewayclass my-gateway-class
Lab 8: Debug DNS Resolution Failure
Goal: Diagnose and fix DNS issues.
bash
# Create a Pod
kubectl run dns-debug --image=busybox --restart=Never -- sleep 3600
# Check resolv.conf
kubectl exec dns-debug -- cat /etc/resolv.conf
# Test resolution
kubectl exec dns-debug -- nslookup kubernetes.default
kubectl exec dns-debug -- nslookup google.com
# Test with trailing dot
kubectl exec dns-debug -- nslookup google.com.
# Check CoreDNS
kubectl get pods -n kube-system -l k8s-app=kube-dns
kubectl logs -n kube-system -l k8s-app=kube-dns --tail=20
# Check NodeLocal DNSCache (if installed)
kubectl get pods -n kube-system -l k8s-app=node-local-dns
# Cleanup
kubectl delete pod dns-debug
Lab 9: Build a Complete Secure Networking Stack
Goal: Default deny + allow + Ingress + DNS.
bash
kubectl create namespace secure-net
# Deploy app
kubectl create deployment web --image=nginx:1.25-alpine -n secure-net --replicas=2
kubectl expose deployment web --port=80 -n secure-net
# Default deny
kubectl apply -n secure-net -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
EOF
# Allow ingress from ingress-nginx
kubectl apply -n secure-net -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-ingress
spec:
podSelector:
matchLabels:
app: web
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: ingress-nginx
ports:
- protocol: TCP
port: 80
EOF
# Allow egress DNS
kubectl apply -n secure-net -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns
spec:
podSelector: {}
policyTypes: [Egress]
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
- protocol: UDP
port: 53
EOF
# Ingress
kubectl apply -n secure-net -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
spec:
ingressClassName: nginx
rules:
- host: secure.local
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
EOF
# Verify
kubectl get all,netpol,ingress -n secure-net
# Cleanup
kubectl delete namespace secure-net
PART 7: INCIDENT MANAGEMENT
35. Networking Incident Post-Mortem Template
text
INCIDENT: CoreDNS Failure - Cluster-Wide Service Discovery Outage
DATE: 2024-01-15
DURATION: 47 minutes
SEVERITY: SEV-1
IMPACT: All services lost DNS resolution. All API calls failed.
TIMELINE:
14:00 - Monitoring alert: CoreDNS QPS dropped to zero
14:03 - On-call acknowledged
14:05 - Identified CoreDNS pods OOMKilled
14:08 - CoreDNS memory limit (170Mi) too low for cluster
14:12 - Increased memory to 500Mi
14:15 - CoreDNS pods restarted
14:20 - DNS resolution restored
14:47 - Incident closed
ROOT CAUSE:
CoreDNS memory limit (170Mi) was too low for 5,000 Pods.
Cache grew beyond limit, OOMKilled, crashlooped.
LESSONS LEARNED:
1. CoreDNS memory must be sized for peak, not average.
2. NodeLocal DNSCache would have prevented this.
3. Alerting must fire on CoreDNS restarts.
ACTION ITEMS:
[ ] Increase CoreDNS memory to 500Mi (Owner: Platform)
[ ] Deploy NodeLocal DNSCache (Owner: Platform)
[ ] Add CoreDNS restart alerting (Owner: SRE)
36. On-Call Runbook: Service Unreachable
text
STEP 1: Check the Service
$ kubectl get svc <service> -o yaml
STEP 2: Check endpoints
$ kubectl get endpoints <service>
$ kubectl get endpointslices -l kubernetes.io/service-name=<service>
STEP 3: Check matching Pods
$ kubectl get pods -l <selector>
$ kubectl get pods -l <selector> -o wide
STEP 4: Check Pod readiness
$ kubectl describe pod <pod> | grep -A3 Readiness
STEP 5: Test DNS
$ kubectl run test --image=busybox --rm -it --restart=Never -- nslookup <service>
STEP 6: Check NetworkPolicy
$ kubectl get networkpolicies -A
STEP 7: Check CNI
$ kubectl get pods -n kube-system -l k8s-app=cilium
$ kubectl logs -n kube-system -l k8s-app=cilium --tail=50
STEP 8: Check kube-proxy
$ kubectl logs -n kube-system -l k8s-app=kube-proxy --tail=50
STEP 9: Escalate
37. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | Cluster-wide networking / DNS outage | 5 min | On-call + Platform + Management |
| SEV-2 | Service unreachable / partial outage | 15 min | On-call + Platform |
| SEV-3 | Single service issue | 1 hour | On-call |
| SEV-4 | Configuration warning | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
38. Junior-Level Questions
| Question | Expected Answer |
| What is CNI? | Plugin that configures Pod networking |
| What are the four Service types? | ClusterIP, NodePort, LoadBalancer, ExternalName |
| What is CoreDNS? | Cluster DNS server |
| What is kube-proxy? | Implements Service load balancing |
| What is NetworkPolicy? | Pod firewall (L3/L4) |
39. Mid-Level Questions
| Question | Expected Answer |
| CNI: Cilium vs Calico? | Cilium: eBPF. Calico: BGP/iptables |
| What is ndots:5? | Search-domain expansion for names with <5 dots |
| What is the 5-second DNS timeout? | conntrack UDP race condition |
| How does NodeLocal DNSCache help? | Local cache, bypasses conntrack |
| What is Gateway API? | Successor to Ingress |
40. Senior-Level Questions
| Question | Expected Answer |
| How do you debug "no endpoints"? | Check selector vs labels |
| How do you implement default deny? | Empty podSelector + policyTypes |
| What is kube-proxy replacement? | eBPF service routing (Cilium) |
| How do you migrate Ingress to Gateway API? | Deploy controller, create Gateway, HTTPRoute |
| How do you handle IP exhaustion? | Prefix delegation, expand CIDR |
41. Staff/Principal Questions
| Question | Expected Answer |
| Design a zero-trust network architecture. | Default deny + L7 policies + mTLS + observability |
| How do you choose a CNI? | Performance, policy, cloud integration, eBPF |
| How do you migrate from Calico to Cilium? | Parallel install, migrate policies, cutover |
| How do you handle multi-cluster networking? | Cluster Mesh, Submariner, global services |
| How do you debug cluster-wide networking? | Check CNI, CoreDNS, kube-proxy, NetworkPolicy |
Summary Cheat Sheet
| Concept | Key Takeaway |
| CNI | Plugin for Pod networking |
| Flannel | Simple VXLAN, no policy |
| Calico | BGP, excellent policy |
| Cilium | eBPF, best performance, L7 |
| AWS VPC CNI | Native VPC IPs, prefix delegation |
| ClusterIP | Internal Service VIP |
| NodePort | External via node port |
| LoadBalancer | Cloud LB |
| ExternalName | DNS alias |
| kube-proxy | Service load balancing |
| iptables | Linear rules, poor scale |
| IPVS | Hash tables, better scale |
| eBPF replacement | O(1) lookups, best |
| CoreDNS | Cluster DNS |
| ndots:5 | Search domain expansion |
| NodeLocal DNSCache | Fixes 5s timeout |
| NetworkPolicy | L3/L4 pod firewall |
| CiliumNetworkPolicy | L7 (HTTP, gRPC) |
| Default deny | Zero-trust baseline |
| Ingress | HTTP routing (maintenance mode) |
| Gateway API | Successor to Ingress |
| Headless Service | Returns Pod IPs |
| Cluster Mesh | Multi-cluster networking |
Stage 8: Storage Deep Dive — The Comprehensive Guide
PART 1: CORE THEORY
1. The Kubernetes Storage Model
Kubernetes storage is built on three core objects that separate what the application needs from how the infrastructure provides it.
The Three Core Objects
| Object | Purpose | Created By |
| PersistentVolume (PV) | The actual storage resource | Admin (static) or CSI driver (dynamic) |
| PersistentVolumeClaim (PVC) | The application's request for storage | Application developer |
| StorageClass | The policy template for provisioning | Cluster admin |
The Mental Model
Applications request storage through a PersistentVolumeClaim. The cluster satisfies that request through a PersistentVolume. A CSI driver is the integration layer that makes the underlying storage system usable from Kubernetes.
Why This Separation Matters
| Without Abstraction | With Abstraction |
| App knows about EBS, GCP PD, NFS | App knows only about PVC |
| Changing storage = changing app | Changing storage = changing StorageClass |
| No portability | Portable across clusters |
| No access control | RBAC for storage |
The Five Questions
When choosing storage, answer these five questions:
- Data path type: Block, file, or object-adjacent?
- Concurrent access: How many Pods need to read/write?
- Performance: What latency and throughput profile?
- Failure domain: Node, zone, or region?
- Operational controls: Snapshots, expansion, backup, retention?
2. CSI (Container Storage Interface)
CSI is the standard plugin model that Kubernetes uses to provision, attach, mount, resize, snapshot, and clone volumes.
What CSI Replaced
Before CSI, storage drivers were in-tree (compiled into Kubernetes). This meant:
- Adding new storage required a Kubernetes release
- Updating drivers required a cluster upgrade
- Vendors couldn't iterate quickly
CSI moves drivers out-of-tree. Vendors maintain their own drivers, and Kubernetes just talks to them via a standard gRPC interface.
The CSI Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ CSI ARCHITECTURE │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Kubernetes Control Plane │ │
│ │ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │ CSI │ │ CSI │ │ │
│ │ │ Controller │ │ Provisioner │ │ │
│ │ │ (StatefulSet│ │ (external) │ │ │
│ │ └──────┬──────┘ └──────┬──────┘ │ │
│ └─────────┼────────────────┼──────────────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ CSI Driver (Deployed by vendor) │ │
│ │ ┌─────────────────────────────────────────────┐ │ │
│ │ │ Controller Plugin (StatefulSet) │ │ │
│ │ │ • CreateVolume, DeleteVolume │ │ │
│ │ │ • ControllerPublishVolume │ │ │
│ │ │ • CreateSnapshot, DeleteSnapshot │ │ │
│ │ └────────────────────┬────────────────────────┘ │ │
│ │ │ │ │
│ │ ┌────────────────────▼────────────────────────┐ │ │
│ │ │ Node Plugin (DaemonSet) │ │ │
│ │ │ • NodeStageVolume, NodePublishVolume │ │ │
│ │ │ • NodeUnpublishVolume │ │ │
│ │ └──────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Major CSI Drivers
| Driver | Cloud | Storage Type |
| ebs.csi.aws.com | AWS | Block (EBS) |
| efs.csi.aws.com | AWS | File (EFS) |
| pd.csi.storage.gke.io | GCP | Block (Persistent Disk) |
| filestore.csi.storage.gke.io | GCP | File (Filestore) |
| disk.csi.azure.com | Azure | Block (Azure Disk) |
| file.csi.azure.com | Azure | File (Azure Files) |
| cephfs.csi.ceph.com | On-prem | File (CephFS) |
| rbd.csi.ceph.com | On-prem | Block (Ceph RBD) |
| driver.longhorn.io | On-prem | Block (Longhorn) |
2026 Recommendations:
- AWS → EBS CSI (gp3)
- GCP → PD CSI (SSD)
- Azure → Disk CSI (Premium)
- On-Prem (<50 nodes) → Longhorn
- On-Prem (50+ nodes) → Rook-Ceph
- RWX needed → Cloud Files or CephFS
3. PersistentVolumes (PV)
A PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically by a StorageClass.
PV Lifecycle
| Phase | Meaning |
| Available | Not yet bound to a PVC |
| Bound | Bound to a PVC |
| Released | PVC deleted, PV not yet reclaimed |
| Failed | Automatic reclamation failed |
Static PV Example
yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: my-pv
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: manual
hostPath:
path: /mnt/data
Reclaim Policies
| Policy | Behavior |
| Retain | Data preserved after PVC deletion; manual cleanup required |
| Delete | PV and underlying storage deleted |
| Recycle | Deprecated; basic scrub |
Volume Modes
| Mode | Behavior |
| Filesystem | Mounted as a directory (default) |
| Block | Raw block device |
4. PersistentVolumeClaims (PVC)
A PersistentVolumeClaim (PVC) is the application's request for storage. It specifies capacity, access mode, and optionally a StorageClass.
PVC Example
yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-claim
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
storageClassName: fast-ssd
PVC Binding
The control plane watches for new PVCs and finds a matching PV (by capacity, access mode, StorageClass). If a PV is found, they are bound. If no PV matches but a StorageClass is specified, a new PV is dynamically provisioned.
PVC Status
| Status | Meaning |
| Pending | Not yet bound |
| Bound | Bound to a PV |
| Lost | PV no longer available |
Using a PVC in a Pod
yaml
spec:
containers:
- name: app
image: myapp:1.0
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: my-claim
PVC Retention
By default, PVCs are not deleted when a StatefulSet is deleted. This preserves data. To delete PVCs, you must do so manually or use a tool like Velero.
5. StorageClasses
A StorageClass is a policy template that defines how volumes are provisioned.
StorageClass Example
yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: fast-ssd
provisioner: ebs.csi.aws.com
parameters:
type: gp3
iops: "3000"
throughput: "125"
encrypted: "true"
reclaimPolicy: Delete
allowVolumeExpansion: true
volumeBindingMode: WaitForFirstConsumer
Key Parameters
| Parameter | Purpose |
| provisioner | CSI driver to use |
| parameters | Driver-specific settings (type, IOPS, encryption) |
| reclaimPolicy | Delete or Retain |
| allowVolumeExpansion | Enable online resize |
| volumeBindingMode | Immediate or WaitForFirstConsumer |
Volume Binding Modes
| Mode | Behavior |
| Immediate | Provision before Pod scheduling |
| WaitForFirstConsumer | Provision after Pod scheduling (topology-aware) |
Production recommendation: Use WaitForFirstConsumer for all storage classes. This ensures volumes are provisioned in the same zone as the Pod.
Default StorageClass
yaml
metadata:
annotations:
storageclass.kubernetes.io/is-default-class: "true"
The default StorageClass is used when a PVC doesn't specify storageClassName.
2026 StorageClass Best Practices
| Practice | Why |
| Use WaitForFirstConsumer | Topology-aware provisioning |
| Enable allowVolumeExpansion | Online resize |
| Set reclaimPolicy: Retain | Data safety for critical workloads |
| Multiple classes | Different performance tiers |
| Mount options | Performance tuning (rsize, wsize, nconnect) |
6. Access Modes
Access modes define how many nodes can mount a volume and whether they can write.
The Four Access Modes
| Mode | Abbreviation | Meaning |
| ReadWriteOnce | RWO | Mounted read-write by a single node |
| ReadOnlyMany | ROX | Mounted read-only by many nodes |
| ReadWriteMany | RWX | Mounted read-write by many nodes |
| ReadWriteOncePod | RWOP | Mounted read-write by a single Pod |
Access Mode by Storage Type
| Storage Type | RWO | ROX | RWX | RWOP |
| Block (EBS, PD, Azure Disk) | ✅ | ❌ | ❌ | ✅ |
| File (EFS, Filestore, Azure Files) | ✅ | ✅ | ✅ | ✅ |
| Ceph RBD | ✅ | ✅ | ❌ | ✅ |
| CephFS | ✅ | ✅ | ✅ | ✅ |
| Longhorn | ✅ | ❌ | ✅ | ✅ |
| Local PV | ✅ | ❌ | ❌ | ✅ |
When to Use Each
| Use Case | Access Mode |
| Database (PostgreSQL, MySQL) | RWO |
| Message queue (Kafka) | RWO |
| Shared CMS media | RWX |
| Read-only config | ROX |
| Single Pod with strict isolation | RWOP |
RWOP (ReadWriteOncePod)
Introduced in Kubernetes 1.22, GA in 1.29. RWOP ensures only one Pod can mount the volume read-write. This is stricter than RWO (which allows multiple Pods on the same node).
yaml
spec:
accessModes:
- ReadWriteOncePod
PART 2: ADVANCED CONCEPTS
7. Volume Snapshots
A VolumeSnapshot is a point-in-time copy of a volume. Snapshots are the foundation for backup, disaster recovery, and cloning.
The Three Objects
| Object | Purpose |
| VolumeSnapshotClass | Snapshot policy (driver, parameters) |
| VolumeSnapshot | The snapshot itself |
| VolumeSnapshotContent | The actual snapshot resource |
Creating a Snapshot
yaml
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
name: my-snapshot
spec:
volumeSnapshotClassName: csi-snapclass
source:
persistentVolumeClaimName: my-claim
Restoring from a Snapshot
yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: restored-claim
spec:
dataSource:
name: my-snapshot
kind: VolumeSnapshot
apiGroup: snapshot.storage.k8s.io
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
Snapshot Requirements
- Kubernetes 1.28+
- Snapshot Controller installed
- Snapshot CRDs installed
- CSI driver with snapshot support
Snapshots vs Backups: The Critical Distinction
Snapshots are not backups. Snapshots are based on Copy-on-Write and are stored in the same storage cluster as the original volume.
| Aspect | Snapshot | Backup |
| Location | Same storage cluster | Different location |
| Protection | Against accidental deletion | Against full storage failure |
| Retention | Short-term | Long-term |
| Tool | CSI Snapshot | Velero, Restic |
Best practice: Use snapshots for fast recovery and backups for data protection.
8. Volume Group Snapshots
Volume Group Snapshots (GA in Kubernetes 1.36) enable atomic snapshots of multiple volumes that need to be consistent.
Why Volume Group Snapshots
For applications with multiple volumes (e.g., a database with data and log volumes), individual snapshots can be inconsistent. Volume Group Snapshots capture all volumes at the same point in time.
Group Snapshot Example
yaml
apiVersion: groupsnapshot.storage.k8s.io/v1
kind: VolumeGroupSnapshot
metadata:
name: db-group-snapshot
spec:
volumeGroupSnapshotClassName: csi-group-snapclass
source:
selector:
matchLabels:
app: database
Use Cases
| Application | Volumes |
| PostgreSQL | Data volume + WAL volume |
| MySQL | Data volume + Binlog volume |
| MongoDB | Data volume + Journal volume |
| Elasticsearch | Data volumes across nodes |
9. Volume Expansion
Volume expansion allows you to increase PVC capacity without downtime when the CSI driver and filesystem support it.
Prerequisites
- Kubernetes 1.24+
- StorageClass with
allowVolumeExpansion: true - CSI driver that supports expansion
- Supported filesystem (XFS, ext3, ext4)
Enabling Expansion
yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: expandable-storage
provisioner: ebs.csi.aws.com
allowVolumeExpansion: true
Expanding a PVC
bash
# Patch the PVC to request more storage
kubectl patch pvc my-data -p '{"spec":{"resources":{"requests":{"storage":"50Gi"}}}}'
The Expansion Flow
text
PVC Request (Increase Size)
│
▼
Controller Expands Backend Volume
│
▼
CSI Driver Resizes Volume
│
▼
Kubelet Resizes Filesystem
│
▼
Volume Ready with New Size
Online vs Offline Expansion
| Type | Requires Pod Restart? | Support |
| Online | ❌ No | Most modern CSI drivers |
| Offline | ✅ Yes | Older drivers |
Production recommendation: Verify online expansion support before relying on it.
10. Ephemeral Volumes
Ephemeral volumes are temporary volumes that exist only for the lifetime of a Pod. They are not persistent.
The Three Types
| Type | Managed By | Use Case |
| emptyDir | Kubernetes | Scratch space, caching |
| Generic ephemeral | Kubernetes | Per-Pod storage |
| CSI ephemeral | CSI driver | Inline volumes |
emptyDir
yaml
spec:
containers:
- name: app
image: myapp:1.0
volumeMounts:
- name: cache
mountPath: /cache
volumes:
- name: cache
emptyDir:
sizeLimit: 1Gi
Important: emptyDir is deleted when the Pod is deleted. If the Pod is restarted, emptyDir may or may not be preserved depending on the node.
Generic Ephemeral
yaml
spec:
volumes:
- name: scratch
ephemeral:
volumeClaimTemplate:
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: fast-ssd
resources:
requests:
storage: 10Gi
The PVC is created automatically and deleted when the Pod is deleted.
CSI Ephemeral
yaml
spec:
volumes:
- name: secrets
csi:
driver: secrets-store.csi.k8s.io
readOnly: true
volumeAttributes:
secretProviderClass: my-secrets
Use case: Secret injection, configuration injection.
11. Local Volumes
Local Persistent Volumes use node-local storage (SSD, NVMe) for high performance and low latency.
When to Use Local Volumes
| Scenario | Local PV? |
| High IOPS database | ✅ Yes |
| AI/ML model loading | ✅ Yes |
| Real-time analytics | ✅ Yes |
| Highly available app | ❌ No |
| Shared data | ❌ No |
Local PV Example
yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: local-pv
spec:
capacity:
storage: 100Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: local-storage
local:
path: /mnt/nvme/data
nodeAffinity:
required:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- node-1
The Node Affinity Requirement
Local PVs must have nodeAffinity to ensure the Pod is scheduled to the correct node.
Local Path Provisioner
For dynamic local PVs, use local-path-provisioner:
yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: local-path
provisioner: rancher.io/local-path
volumeBindingMode: WaitForFirstConsumer
Local Volume Limitations
| Limitation | Impact |
| No HA | Node failure = data loss |
| No replication | Manual backup required |
| Node affinity | Pods must schedule to the right node |
| No expansion | Capacity fixed |
12. Volume Cloning
Volume cloning creates a new volume from an existing PVC.
yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: cloned-claim
spec:
dataSource:
name: original-claim
kind: PersistentVolumeClaim
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
Use cases: Testing, development, data analysis on a copy of production.
13. OCI VolumeSource
OCI VolumeSource (GA in Kubernetes 1.36) mounts OCI registry artifacts directly as volumes.
Why OCI VolumeSource
Traditionally, pulling artifacts (models, datasets, configs) required init containers or custom logic. OCI VolumeSource mounts them directly as volumes.
Example
yaml
spec:
volumes:
- name: model
oci:
image: "registry.example.com/ml-models/bert:latest"
pullPolicy: IfNotPresent
Use Cases
| Use Case | Benefit |
| AI/ML models | Pull models without init containers |
| Configuration bundles | Versioned configs via OCI |
| Static assets | Mount frontend builds |
| WebAssembly modules | Distribute WASM via OCI |
14. Dynamic Resource Allocation (DRA)
DRA (GA in Kubernetes 1.36) is a new API for requesting arbitrary resources (GPUs, FPGAs, specialized hardware) with more flexibility than device plugins.
DRA for Storage
DRA can be used for:
- NVMe devices with specific performance characteristics
- Persistent memory (PMEM)
- Hardware accelerators with storage requirements
DRA Example
yaml
apiVersion: resource.k8s.io/v1
kind: ResourceClaim
metadata:
name: my-claim
spec:
devices:
requests:
- name: nvme
deviceClassName: high-iops-nvme
count: 1
15. Mount Options and Performance Tuning
Mount options significantly impact storage performance.
Common Mount Options
| Option | Effect | Use Case |
| noatime | Don't update access time | Read-heavy workloads |
| nodiratime | Don't update directory access time | Same as noatime |
| nconnect | Multiple TCP connections (NFS) | High throughput |
| rsize / wsize | Read/write size (NFS) | Performance tuning |
| actimeo | Attribute cache timeout | Metadata-heavy workloads |
| nodiratime | No directory atime | Performance |
StorageClass with Mount Options
yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: high-perf
provisioner: file.csi.azure.com
parameters:
protocol: nfs
mountOptions:
- nconnect=4
- rsize=262144
- wsize=262144
- actimeo=30
Performance Tuning by Workload
| Workload | Mount Options |
| Database | noatime, nodiratime |
| NFS file share | nconnect=4, rsize=256K, wsize=256K |
| Read-only content | noatime, ro |
| High-throughput | nconnect=8 |
PART 3: PRODUCTION FAILURE MODES
16. Top 10 Storage Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | PVC stuck Pending | PVC never binds | No matching PV, StorageClass issue | Check describe Events |
| 2 | Volume attach failure | Pod stuck ContainerCreating | Volume in wrong zone, node limit | Check Events, zone |
| 3 | Volume mount failure | Pod fails to start | Filesystem corruption, mount options | Check Events, node logs |
| 4 | Expansion failure | PVC resize stuck | Driver doesn't support, filesystem issue | Check Events, driver |
| 5 | Snapshot creation failure | Snapshot stuck | SnapshotClass missing, driver issue | Check Events, CRDs |
| 6 | Data loss | Data gone after PVC delete | Delete reclaim policy | Use Retain |
| 7 | Volume stuck in Released | PV not reusable | Retain policy, manual cleanup needed | Delete PV manually |
| 8 | IOPS throttling | Slow performance | Storage limits | Increase IOPS tier |
| 9 | Zone mismatch | Pod can't mount | Pod and volume in different zones | Use WaitForFirstConsumer |
| 10 | Local PV node failure | Data unavailable | Node-local storage | Backup, replication |
17. Storage Debugging Runbook
"PVC is Pending" — Step-by-Step
text
STEP 1: Check PVC status
$ kubectl get pvc <pvc-name>
$ kubectl describe pvc <pvc-name>
# Read Events
STEP 2: Check StorageClass
$ kubectl get storageclass
$ kubectl get storageclass <class-name> -o yaml
# Verify provisioner, parameters
STEP 3: Check CSI driver
$ kubectl get pods -n kube-system | grep csi
$ kubectl logs -n kube-system <csi-controller-pod>
STEP 4: Check for volume attach issues
$ kubectl get volumeattachments
$ kubectl describe volumeattachment <name>
STEP 5: Check node limits
$ kubectl describe node <node> | grep -A5 "Attachable Volumes"
STEP 6: Check zone
# For zonal storage (EBS, PD, Azure Disk)
# Pod must be in same zone as volume
STEP 7: Check expansion (if resizing)
$ kubectl describe pvc <pvc-name>
# Look for FileSystemResizePending
STEP 8: Check snapshot (if restoring)
$ kubectl get volumesnapshot <snap-name>
$ kubectl describe volumesnapshot <snap-name>
STEP 9: Escalate
Quick Diagnostic Table
| Symptom | First Check | Then |
| PVC Pending | kubectl describe pvc | Check StorageClass |
| Volume attach fail | kubectl get volumeattachments | Check zone |
| Mount fail | Pod Events | Node logs |
| Expansion stuck | kubectl describe pvc | Check driver support |
| Snapshot fail | kubectl describe volumesnapshot | Check SnapshotClass |
18. Blast Radius Analysis
What Happens When Storage Fails?
| Component | Impact | Severity |
| Storage backend down | All stateful workloads fail | SEV-1 |
| CSI driver down | New volumes can't provision | SEV-1 |
| Volume attach failure | Pods stuck | SEV-2 |
| Data corruption | Data loss | SEV-1 |
| Zone failure | Zonal volumes unavailable | SEV-1 |
| Snapshot failure | Backup gaps | SEV-2 |
Mitigation Strategies
| Strategy | Implementation |
| Replicated storage | Ceph, Longhorn |
| Regular backups | Velero |
| Snapshots | Fast recovery |
| Multi-AZ | Zone-aware provisioning |
| Retain policy | Prevent accidental deletion |
PART 4: CAPACITY PLANNING & COST MODELING
19. Storage Capacity and IOPS Modeling
Capacity Planning
text
Required capacity = (Data size) × (Growth factor) × (Replication factor)
Example:
- 100 GB data
- 20% annual growth
- 3x replication
- 3-year capacity = 100 × 1.2³ × 3 = 518 GB
IOPS Planning
| Storage Type | IOPS per GB | Latency |
| gp2 (AWS) | 3 | ~10ms |
| gp3 (AWS) | 3,000 baseline | ~5ms |
| io2 (AWS) | 500:1 | <1ms |
| Premium SSD (Azure) | 120 | ~5ms |
| Ultra Disk (Azure) | Custom | <1ms |
Performance Tiers
| Tier | IOPS | Throughput | Use Case |
| Standard | 500 | 50 MB/s | Dev/test |
| Performance | 3,000–16,000 | 125–500 MB/s | Production |
| Ultra | 64,000+ | 1,000+ MB/s | Databases, AI |
20. Storage Tiering and Cost Optimization
Storage Tiers
| Tier | Type | Cost/GB | Use Case |
| Hot | SSD/NVMe | $$$ | Databases, active data |
| Warm | SSD | $$ | Web apps |
| Cold | HDD | $ | Archives |
| Archive | Object | ¢ | Long-term retention |
Cost Optimization Tactics
| Tactic | Savings |
| Right-size volumes | 30–50% |
| Delete orphaned PVCs | 20–40% |
| Use gp3 instead of gp2 | 20% |
| Use snapshots for backups | 50% vs full copies |
| Tier cold data | 60–80% |
Orphaned PVC Detection
bash
# Find PVCs not mounted by any Pod
kubectl get pvc -A -o json | jq -r '
.items[] |
select(.status.phase == "Bound") |
"\(.metadata.namespace)/\(.metadata.name)"
'
21. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Storage SLA Design
| Target | Architecture |
| 99.9% | Single-AZ storage, basic backups |
| 99.99% | Multi-AZ storage, snapshots, Velero |
| 99.999% | Replicated storage (Ceph), cross-region backup |
RPO and RTO
| Metric | Meaning | Depends On |
| RPO (Recovery Point Objective) | Max data loss | Backup frequency |
| RTO (Recovery Time Objective) | Max downtime | Recovery speed |
| Strategy | RPO | RTO |
| Snapshots | Minutes | Minutes |
| Velero | Hours | Hours |
| Replication | Seconds | Minutes |
| Active-Active | Zero | Zero |
PART 5: ARCHITECTURE & STRATEGY
22. Storage Architecture Patterns
Pattern 1: Simple (Single AZ)
text
┌─────────────────────────────────────────────────────────────┐
│ Single AZ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Pod │ │ Pod │ │ Pod │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │ │
│ └────────────────┴────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ EBS/PD │ │
│ │ (RWO) │ │
│ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
Use case: Dev, single-region.
Pattern 2: Multi-AZ (HA)
text
┌─────────────────────────────────────────────────────────────┐
│ Multi-AZ │
│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ AZ-a │ │ AZ-b │ │ AZ-c │ │
│ │ Pod │ │ Pod │ │ Pod │ │
│ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ EBS │ │ EBS │ │ EBS │ │
│ └───────────┘ └───────────┘ └───────────┘ │
└─────────────────────────────────────────────────────────────┘
Use case: Production HA.
Pattern 3: Replicated Storage (Ceph)
text
┌─────────────────────────────────────────────────────────────┐
│ Replicated Storage (Ceph) │
│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Node 1 │ │ Node 2 │ │ Node 3 │ │
│ │ OSD │ │ OSD │ │ OSD │ │
│ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ └──────────────────┴──────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ RBD/CephFS │ │
│ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
Use case: On-prem, high availability.
23. Disaster Recovery for Stateful Workloads
DR Strategies
| Strategy | RPO | RTO | Cost |
| Backup/Restore | Hours | Hours | $ |
| Snapshot | Minutes | Minutes | $$ |
| Replication | Seconds | Minutes | $$$ |
| Active-Active | Zero | Zero | $$$$ |
Velero for Backup
Velero is the standard tool for Kubernetes backup and restore.
bash
# Install Velero
velero install \
--provider aws \
--bucket my-backup-bucket \
--secret-file ./credentials-velero \
--use-volume-snapshots=true
# Create a backup
velero backup create my-backup --include-namespaces production
# Restore
velero restore create --from-backup my-backup
Velero with CSI Snapshots
Velero can use CSI snapshots for volume backup.
yaml
apiVersion: velero.io/v1
kind: Backup
metadata:
name: my-backup
spec:
includedNamespaces:
- production
snapshotVolumes: true
volumeSnapshotLocations:
- my-snapshot-location
Backup Best Practices
| Practice | Why |
| Back up regularly | RPO |
| Test restores | Verify backups work |
| Store offsite | Protect against site failure |
| Encrypt backups | Security |
| Automate | Consistency |
24. Compliance & Security for Storage
| Framework | Storage Requirement |
| PCI-DSS | Encryption at rest, access controls |
| HIPAA | Encryption, audit trails |
| SOC2 | Change management, monitoring |
| GDPR | Data residency, right to erasure |
| FedRAMP | FIPS 140-2 encryption |
Encryption
| Layer | How |
| At rest | Storage encryption (EBS, PD, Azure Disk) |
| In transit | TLS for network storage |
| Kubernetes Secrets | etcd encryption |
Encryption at Rest Example
yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: encrypted
provisioner: ebs.csi.aws.com
parameters:
encrypted: "true"
kmsKeyId: "arn:aws:kms:us-east-1:123456789:key/abc"
PART 6: HANDS-ON LABS
Lab 1: Create a PV and PVC
Goal: Understand static provisioning.
bash
# Create a PV
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolume
metadata:
name: manual-pv
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: manual
hostPath:
path: /mnt/manual-pv
EOF
# Create a PVC
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: manual-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: manual
EOF
# Check binding
kubectl get pv,pvc
kubectl describe pvc manual-pvc
# Create a Pod using the PVC
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: pv-pod
spec:
containers:
- name: app
image: busybox
command: ["sh", "-c", "echo 'Hello from PV' > /data/test.txt && sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: manual-pvc
EOF
sleep 5
kubectl exec pv-pod -- cat /data/test.txt
# Cleanup
kubectl delete pod pv-pod
kubectl delete pvc manual-pvc
kubectl delete pv manual-pv
Lab 2: Dynamic Provisioning with StorageClass
Goal: Provision storage automatically.
bash
# Create a StorageClass
cat <<'EOF' | kubectl apply -f -
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: dynamic-sc
provisioner: rancher.io/local-path
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
EOF
# Create a PVC
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: dynamic-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: dynamic-sc
EOF
# Check (may be Pending until Pod uses it)
kubectl get pvc dynamic-pvc
# Create a Pod
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: dynamic-pod
spec:
containers:
- name: app
image: busybox
command: ["sh", "-c", "sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: dynamic-pvc
EOF
sleep 10
kubectl get pvc dynamic-pvc
# Should now be Bound
# Cleanup
kubectl delete pod dynamic-pod
kubectl delete pvc dynamic-pvc
kubectl delete storageclass dynamic-sc
Lab 3: Access Modes
Goal: Understand RWO vs RWX.
bash
# Create a StorageClass that supports RWX (e.g., NFS, EFS)
# For local testing, we'll simulate with hostPath and RWO
# Create a PVC with RWO
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: rwo-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: dynamic-sc
EOF
# Create a Pod using it
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: rwo-pod
spec:
containers:
- name: app
image: busybox
command: ["sh", "-c", "sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: rwo-pvc
EOF
# Try to create a second Pod using the same RWO PVC (may fail on multi-node)
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: rwo-pod-2
spec:
containers:
- name: app
image: busybox
command: ["sh", "-c", "sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: rwo-pvc
EOF
sleep 10
kubectl get pods
# On a single-node cluster, both may work. On multi-node, RWO restricts.
# Cleanup
kubectl delete pod rwo-pod rwo-pod-2 --ignore-not-found
kubectl delete pvc rwo-pvc
Lab 4: Volume Snapshots and Restore
Goal: Create and restore from a snapshot.
Prerequisites: Snapshot CRDs and controller installed.
bash
# Install snapshot CRDs
kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/master/client/config/crd/snapshot.storage.k8s.io_volumesnapshotclasses.yaml
kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/master/client/config/crd/snapshot.storage.k8s.io_volumesnapshotcontents.yaml
kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/master/client/config/crd/snapshot.storage.k8s.io_volumesnapshots.yaml
# Create a PVC and Pod
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: snap-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: dynamic-sc
---
apiVersion: v1
kind: Pod
metadata:
name: snap-pod
spec:
containers:
- name: app
image: busybox
command: ["sh", "-c", "echo 'Original data' > /data/file.txt && sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: snap-pvc
EOF
sleep 10
kubectl exec snap-pod -- cat /data/file.txt
# Create a VolumeSnapshotClass
cat <<'EOF' | kubectl apply -f -
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshotClass
metadata:
name: csi-snapclass
driver: hostpath.csi.k8s.io
deletionPolicy: Delete
EOF
# Create a snapshot
cat <<'EOF' | kubectl apply -f -
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
name: snap-1
spec:
volumeSnapshotClassName: csi-snapclass
source:
persistentVolumeClaimName: snap-pvc
EOF
sleep 10
kubectl get volumesnapshot
# Modify original data
kubectl exec snap-pod -- sh -c "echo 'Modified data' > /data/file.txt"
# Restore from snapshot
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: restored-pvc
spec:
dataSource:
name: snap-1
kind: VolumeSnapshot
apiGroup: snapshot.storage.k8s.io
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: dynamic-sc
EOF
# Verify
sleep 10
kubectl get pvc restored-pvc
# Cleanup
kubectl delete pod snap-pod
kubectl delete pvc snap-pvc restored-pvc
kubectl delete volumesnapshot snap-1
kubectl delete volumesnapshotclass csi-snapclass
Lab 5: Online Volume Expansion
Goal: Expand a PVC without downtime.
bash
# Create a PVC with a StorageClass that allows expansion
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: expand-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: dynamic-sc
EOF
# Create a Pod
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: expand-pod
spec:
containers:
- name: app
image: busybox
command: ["sh", "-c", "sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: expand-pvc
EOF
sleep 10
kubectl get pvc expand-pvc
# Expand (online)
kubectl patch pvc expand-pvc -p '{"spec":{"resources":{"requests":{"storage":"2Gi"}}}}'
# Monitor
kubectl get pvc expand-pvc -w
# Cleanup
kubectl delete pod expand-pod
kubectl delete pvc expand-pvc
Lab 6: Ephemeral Volumes
Goal: Use emptyDir and generic ephemeral volumes.
bash
# emptyDir
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: empty-dir-pod
spec:
containers:
- name: app
image: busybox
command: ["sh", "-c", "echo 'scratch data' > /cache/test.txt && sleep 3600"]
volumeMounts:
- name: cache
mountPath: /cache
volumes:
- name: cache
emptyDir:
sizeLimit: 1Gi
EOF
sleep 5
kubectl exec empty-dir-pod -- cat /cache/test.txt
# Generic ephemeral volume
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: generic-ephemeral-pod
spec:
containers:
- name: app
image: busybox
command: ["sh", "-c", "echo 'ephemeral data' > /data/test.txt && sleep 3600"]
volumeMounts:
- name: scratch
mountPath: /data
volumes:
- name: scratch
ephemeral:
volumeClaimTemplate:
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: dynamic-sc
resources:
requests:
storage: 1Gi
EOF
sleep 10
kubectl exec generic-ephemeral-pod -- cat /data/test.txt
# Cleanup
kubectl delete pod empty-dir-pod generic-ephemeral-pod
Lab 7: Local Persistent Volumes
Goal: Use node-local storage.
bash
# Create a local PV (adjust node name)
NODE=$(kubectl get nodes -o jsonpath='{.items[0].metadata.name}')
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: PersistentVolume
metadata:
name: local-pv
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: local-storage
local:
path: /mnt/local-data
nodeAffinity:
required:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- $NODE
EOF
# Create a PVC
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: local-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: local-storage
EOF
kubectl get pv,pvc
# Create a Pod
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: local-pod
spec:
containers:
- name: app
image: busybox
command: ["sh", "-c", "echo 'local data' > /data/test.txt && sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: local-pvc
EOF
sleep 5
kubectl exec local-pod -- cat /data/test.txt
# Cleanup
kubectl delete pod local-pod
kubectl delete pvc local-pvc
kubectl delete pv local-pv
Lab 8: Velero Backup and Restore
Goal: Back up and restore a namespace.
Prerequisites: Velero installed with a storage backend (S3, MinIO).
bash
# Install Velero (example with MinIO)
velero install \
--provider aws \
--plugins velero/velero-plugin-for-aws:v1.9.0 \
--bucket velero \
--secret-file ./credentials-velero \
--use-volume-snapshots=false \
--backup-location-config region=minio,s3ForcePathStyle="true",s3Url=http://minio.velero.svc:9000
# Create a namespace with resources
kubectl create namespace backup-test
kubectl create deployment nginx --image=nginx -n backup-test
kubectl expose deployment nginx --port=80 -n backup-test
# Create a backup
velero backup create test-backup --include-namespaces backup-test
# Check backup
velero backup describe test-backup
velero backup logs test-backup
# Delete the namespace
kubectl delete namespace backup-test
# Restore
velero restore create --from-backup test-backup
# Verify
kubectl get all -n backup-test
# Cleanup
kubectl delete namespace backup-test
velero backup delete test-backup
Lab 9: Complete Stateful Application
Goal: Deploy a StatefulSet with PVCs, snapshots, and backup.
bash
kubectl create namespace stateful-lab
# Headless Service
cat <<'EOF' | kubectl apply -n stateful-lab -f -
apiVersion: v1
kind: Service
metadata:
name: db-headless
spec:
clusterIP: None
selector:
app: db
ports:
- port: 5432
name: postgres
EOF
# StatefulSet with PVC template
cat <<'EOF' | kubectl apply -n stateful-lab -f -
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: db
spec:
serviceName: db-headless
replicas: 3
selector:
matchLabels:
app: db
template:
metadata:
labels:
app: db
spec:
containers:
- name: postgres
image: postgres:16-alpine
env:
- name: POSTGRES_PASSWORD
value: secret
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
ports:
- containerPort: 5432
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: dynamic-sc
resources:
requests:
storage: 1Gi
EOF
# Wait for pods
kubectl wait -n stateful-lab --for=condition=Ready pod -l app=db --timeout=180s
# Check PVCs
kubectl get pvc -n stateful-lab
# Write data to db-0
kubectl exec -n stateful-lab db-0 -- psql -U postgres -c "CREATE TABLE test (id int); INSERT INTO test VALUES (1);"
# Verify
kubectl exec -n stateful-lab db-0 -- psql -U postgres -c "SELECT * FROM test;"
# Cleanup
kubectl delete namespace stateful-lab
kubectl delete pvc -n stateful-lab --all --ignore-not-found
PART 7: INCIDENT MANAGEMENT
34. Storage Incident Post-Mortem Template
text
INCIDENT: PVC Expansion Failure - Database Disk Full
DATE: 2024-01-15
DURATION: 47 minutes
SEVERITY: SEV-1
IMPACT: PostgreSQL database unable to write. All API calls failed.
TIMELINE:
14:00 - Alert: Database disk usage 100%
14:03 - On-call acknowledged
14:05 - Attempted to expand PVC
14:08 - Expansion stuck in "Resizing" state
14:10 - Identified CSI driver doesn't support online expansion
14:15 - Stopped database Pod
14:20 - Expansion completed offline
14:25 - Restarted database
14:30 - Service restored
14:47 - Incident closed
ROOT CAUSE:
CSI driver didn't support online expansion for this volume type.
No monitoring on storage capacity.
LESSONS LEARNED:
1. Verify online expansion support before relying on it.
2. Alert at 80% disk usage, not 100%.
3. Test expansion in staging.
ACTION ITEMS:
[ ] Add storage capacity alerting at 80% (Owner: SRE)
[ ] Verify all CSI drivers support online expansion (Owner: Platform)
[ ] Document offline expansion procedure (Owner: Platform)
35. On-Call Runbook: Storage Failures
text
SYMPTOM: Storage-related failures.
STEP 1: Identify the issue
$ kubectl get pvc -A | grep -v Bound
$ kubectl get pv | grep -v Bound
STEP 2: Check PVC status
$ kubectl describe pvc <name>
# Read Events
STEP 3: Check CSI driver
$ kubectl get pods -n kube-system | grep csi
$ kubectl logs -n kube-system <csi-pod>
STEP 4: Check volume attachments
$ kubectl get volumeattachments
$ kubectl describe volumeattachment <name>
STEP 5: Check node capacity
$ kubectl describe node <node> | grep -A5 "Attachable Volumes"
STEP 6: Check zone
# For zonal storage, verify Pod and volume are in same zone
STEP 7: Check expansion (if resizing)
$ kubectl describe pvc <name>
# Look for FileSystemResizePending
STEP 8: Check snapshots (if restoring)
$ kubectl get volumesnapshot -A
$ kubectl describe volumesnapshot <name>
STEP 9: Escalate
36. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | Data loss / all stateful workloads down | 5 min | On-call + Platform + Management |
| SEV-2 | Single PVC stuck / expansion failure | 15 min | On-call + Platform |
| SEV-3 | Slow storage performance | 1 hour | On-call |
| SEV-4 | Capacity planning warning | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
37. Junior-Level Questions
| Question | Expected Answer |
| What is a PV? | PersistentVolume — the storage resource |
| What is a PVC? | PersistentVolumeClaim — the application request |
| What is a StorageClass? | Template for provisioning |
| What is CSI? | Container Storage Interface |
| What are the access modes? | RWO, ROX, RWX, RWOP |
38. Mid-Level Questions
| Question | Expected Answer |
| Static vs dynamic provisioning? | Static: admin creates PV. Dynamic: StorageClass creates PV. |
| What is WaitForFirstConsumer? | Provision volume in Pod's zone |
| What is a VolumeSnapshot? | Point-in-time copy of a volume |
| How do you expand a PVC? | Patch PVC with new size (if allowed) |
| What is emptyDir? | Ephemeral volume for scratch space |
39. Senior-Level Questions
| Question | Expected Answer |
| Snapshot vs backup? | Snapshot is same storage cluster; backup is offsite |
| How do you handle zone failures? | Multi-AZ storage, WaitForFirstConsumer |
| What is Volume Group Snapshot? | Atomic multi-volume snapshot (K8s 1.36 GA) |
| How do you secure storage? | Encryption at rest, RBAC, NetworkPolicy |
| How do you optimize storage cost? | Right-size, tier, delete orphans |
40. Staff/Principal Questions
| Question | Expected Answer |
| Design a storage architecture for 99.999%. | Replicated storage, multi-AZ, cross-region backup |
| How do you migrate storage between clusters? | Velero, snapshots, StorageClass migration |
| How do you choose a CSI driver? | Workload type, performance, cloud, RWX needs |
| How do you handle stateful workload DR? | Velero + snapshots + replication |
| How do you enforce storage compliance? | Encryption, RBAC, audit logging |
Summary Cheat Sheet
| Concept | Key Takeaway |
| PV | Storage resource (admin-created) |
| PVC | Application request for storage |
| StorageClass | Template for dynamic provisioning |
| CSI | Standard plugin model for storage |
| RWO | Single node read-write |
| ROX | Many nodes read-only |
| RWX | Many nodes read-write |
| RWOP | Single Pod read-write |
| VolumeSnapshot | Point-in-time copy |
| VolumeGroupSnapshot | Atomic multi-volume (K8s 1.36 GA) |
| Expansion | Online resize with allowVolumeExpansion |
| emptyDir | Ephemeral scratch space |
| Generic ephemeral | Per-Pod PVC |
| Local PV | Node-local storage (high performance) |
| OCI VolumeSource | Mount OCI artifacts (K8s 1.36 GA) |
| DRA | Dynamic Resource Allocation (GA) |
| Velero | Backup and restore |
| Retain | Preserve data after PVC delete |
| Delete | Delete storage after PVC delete |
| WaitForFirstConsumer | Zone-aware provisioning |
| nconnect | Multiple NFS connections |
| Snapshots ≠ Backups | Snapshots same cluster; backups offsite |
Stage 9: Cluster Extensibility (CRDs, Controllers, Operators) — The Comprehensive Guide
PART 1: CORE THEORY
1. What is Cluster Extensibility?
Kubernetes is designed to be extended. The core API is intentionally limited, and the extension mechanisms allow you to add new resource types, new controllers, and new behaviors without modifying Kubernetes itself.
The Three Extension Mechanisms
| Mechanism | What It Extends | Use Case |
| Custom Resource Definitions (CRDs) | The API | New resource types |
| Admission Webhooks | The request pipeline | Validation, mutation |
| Aggregation Layer | The API server | Full custom API servers |
Why Extensibility Matters
| Without Extensibility | With Extensibility |
| Fork Kubernetes for new features | Add features via CRDs |
| Wait for upstream releases | Ship features independently |
| Limited to core resources | Unlimited custom resources |
| No domain-specific automation | Operators for every use case |
The Extensibility Spectrum
text
Simple Complex
│ │
▼ ▼
CRDs only → CRDs + Webhooks → Full Operators → Aggregated APIs
Rule of thumb: Start with CRDs. Add webhooks when you need validation. Build an Operator when you need automation.
2. Custom Resource Definitions (CRDs)
A Custom Resource Definition (CRD) extends the Kubernetes API with your own resource type. Once installed, your custom resources behave like built-in Kubernetes resources.
CRD Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ CRD ARCHITECTURE │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Kubernetes API │ │
│ │ ┌─────────────┐ ┌─────────────────────────────┐ │ │
│ │ │ CRD │───►│ Extended API │ │ │
│ │ │ Definition │ │ • /apis/example.com/v1/ │ │ │
│ │ └─────────────┘ │ webapps │ │ │
│ │ └─────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Custom Resources (CRs) │ │
│ │ • my-webapp │ │
│ │ • my-database │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Controller (Watch → Reconcile → Manage) │ │
│ │ • Watches CR events │ │
│ │ • Reconciles desired vs actual state │ │
│ │ • Creates/updates Deployments, Services, etc. │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
A Basic CRD
yaml
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: webapps.example.com # <plural>.<group>
spec:
group: example.com
names:
kind: WebApp
listKind: WebAppList
plural: webapps
singular: webapp
shortNames:
- wa
scope: Namespaced # or Cluster
versions:
- name: v1
served: true # API version enabled
storage: true # Primary storage version
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required:
- image
- replicas
properties:
image:
type: string
description: Container image
replicas:
type: integer
minimum: 1
maximum: 100
default: 1
port:
type: integer
default: 8080
status:
type: object
properties:
availableReplicas:
type: integer
conditions:
type: array
items:
type: object
properties:
type:
type: string
status:
type: string
lastTransitionTime:
type: string
format: date-time
additionalPrinterColumns: # Extra columns for kubectl get
- name: Image
type: string
jsonPath: .spec.image
- name: Replicas
type: integer
jsonPath: .spec.replicas
- name: Available
type: integer
jsonPath: .status.availableReplicas
- name: Age
type: date
jsonPath: .metadata.creationTimestamp
subresources:
status: {} # Enable status subresource
# scale: # Enable scale subresource
# specReplicasPath: .spec.replicas
# statusReplicasPath: .status.availableReplicas
Creating a Custom Resource
yaml
apiVersion: example.com/v1
kind: WebApp
metadata:
name: my-webapp
namespace: production
spec:
image: nginx:1.25
replicas: 3
port: 80
CRD Validation
CRDs use OpenAPI v3 schema for validation:
| Validation | Example |
| Type | type: string |
| Required | required: [image, replicas] |
| Minimum/Maximum | minimum: 1, maximum: 100 |
| Pattern | pattern: "^[a-z0-9-]+$" |
| Enum | enum: [dev, staging, prod] |
| Default | default: 1 |
CRD Scopes
| Scope | Behavior |
| Namespaced | CRs exist in namespaces |
| Cluster | CRs are cluster-wide |
CRD Best Practices
| Practice | Why |
| Use OpenAPI schema | Validation, documentation |
| Enable status subresource | Separate spec from status |
| Set additionalPrinterColumns | Better kubectl get output |
| Use shortNames | Convenience |
| Version from the start | Plan for evolution |
| Avoid over-nesting | Keep schemas simple |
3. The Controller Pattern
A controller is a control loop that watches resources and reconciles the desired state with the actual state.
The Watch-Queue-Reconcile Pattern
text
┌─────────────────────────────────────────────────────────────┐
│ CONTROLLER PATTERN │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Informer │ │
│ │ • Watches API server for changes │ │
│ │ • Maintains local cache │ │
│ │ • Enqueues events to WorkQueue │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ WorkQueue │ │
│ │ • Rate-limited queue │ │
│ │ • Deduplicates events │ │
│ │ • Retries failed items │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Reconciler (Worker Goroutines) │ │
│ │ • Processes one item at a time │ │
│ │ • Reads current state from cache │ │
│ │ • Compares desired vs actual │ │
│ │ • Acts to reconcile │ │
│ │ • Updates status │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
The Informer
The Informer is the core of the controller pattern. It:
- Watches the API server for changes to specific resources
- Maintains a local cache (Indexer) for fast reads
- Enqueues events to the WorkQueue via event handlers
Informers watch the API server and mirror objects into a local cache. Event handlers boil every change down to a small key that means "go reconcile this thing."
The WorkQueue
The WorkQueue decouples event reception from processing. It provides:
| Feature | Purpose |
| Rate limiting | Prevents overwhelming the controller |
| Deduplication | Collapses multiple events for the same object |
| Retry | Re-queues failed items with backoff |
The RateLimitingInterface extends DelayingInterface with rate limiter functionality. When the number of insertions exceeds the rate limiter rules, the object is pushed to a delayed queue for processing.
The Reconciler
The Reconciler contains the actual logic:
go
func (r *WebAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
// 1. Fetch the custom resource
var webapp examplev1.WebApp
if err := r.Get(ctx, req.NamespacedName, &webapp); err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, nil // Resource deleted
}
return ctrl.Result{}, err
}
// 2. Check if deployment exists
var deployment appsv1.Deployment
err := r.Get(ctx, types.NamespacedName{
Name: webapp.Name,
Namespace: webapp.Namespace,
}, &deployment)
if apierrors.IsNotFound(err) {
// 3. Create deployment
deployment = r.deploymentForWebApp(&webapp)
if err := r.Create(ctx, &deployment); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{Requeue: true}, nil
}
if err != nil {
return ctrl.Result{}, err
}
// 4. Update deployment if needed
if r.needsUpdate(&deployment, &webapp) {
r.updateDeployment(&deployment, &webapp)
if err := r.Update(ctx, &deployment); err != nil {
return ctrl.Result{}, err
}
}
// 5. Update status
webapp.Status.AvailableReplicas = deployment.Status.AvailableReplicas
if err := r.Status().Update(ctx, &webapp); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
The Reconciliation Guarantees
| Guarantee | Meaning |
| Level-triggered | Reconcile runs on the current state, not events |
| Idempotent | Running multiple times produces the same result |
| Eventually consistent | The system converges to desired state |
| Optimistic concurrency | Uses resourceVersion for conflict detection |
The Operator Pattern
An Operator is a controller for a specific application. It encodes the Day 2 operations that a human operator would perform.
| Standard Controller | Operator |
| Manages one resource type | Manages a complex application |
| Generic logic | Domain-specific knowledge |
| No external coordination | Coordinates multiple resources |
| Example: ReplicaSet controller | Example: PostgreSQL operator |
Operators extend Kubernetes to manage complex applications automatically. Instead of writing scripts and runbooks, you encode operational knowledge into code that runs in your cluster.
Operators were introduced to address Day 2 operations such as backups, version upgrades, and automated failure recovery.
4. Operators
An Operator is a controller that encodes human operational knowledge for a specific application.
What Operators Automate
| Operation | What It Does |
| Deployment | Creates and configures all resources |
| Scaling | Adjusts replicas based on load |
| Backup | Scheduled backups to object storage |
| Restore | Point-in-time recovery |
| Upgrade | Orchestrates rolling upgrades |
| Failover | Promotes replicas on primary failure |
| Configuration | Manages config changes safely |
Operator Maturity Model
| Level | Capability |
| 1. Basic Install | Automated provisioning |
| 2. Seamless Upgrades | Patch and minor upgrades |
| 3. Full Lifecycle | Backup, restore, failover |
| 4. Deep Insights | Metrics, alerts, logs |
| 5. Auto Pilot | Auto-scaling, auto-tuning, auto-recovery |
When to Build an Operator
| Scenario | Build Operator? |
| Complex stateful app | ✅ Yes |
| Multi-step workflows | ✅ Yes |
| Auto-remediation | ✅ Yes |
| Simple stateless app | ❌ No (use Deployment) |
| One-time setup | ❌ No (use Job) |
| Simple config change | ❌ No (use ConfigMap) |
Operators are best for long-lived, stateful responsibilities. Use them when you need continuous reconciliation: if resources drift or are deleted, the operator enforces desired state.
Real-World Operators
| Operator | Purpose |
| Prometheus Operator | Manages Prometheus, Alertmanager, ServiceMonitors |
| cert-manager | Automates TLS certificate management |
| Istio Operator | Manages Istio service mesh |
| PostgreSQL Operator | Manages PostgreSQL clusters |
| Kafka Operator | Manages Kafka clusters |
| Crossplane | Manages cloud resources from Kubernetes |
PART 2: ADVANCED CONCEPTS
5. Admission Webhooks
Admission webhooks intercept API requests before objects are persisted. They are the enforcement layer for policies.
The Three Webhook Types
| Type | Purpose | Can Modify? | Order |
| Mutating | Modify objects | ✅ Yes | First |
| Validating | Allow/deny | ❌ No | Second |
| Conversion | Convert between CRD versions | ✅ Yes | During read/write |
The Admission Flow
text
API Request
│
▼
Authentication (Who are you?)
│
▼
Authorization (What can you do?)
│
▼
Mutating Admission (Modify the object)
│
▼
Schema Validation (OpenAPI)
│
▼
Validating Admission (Allow or deny)
│
▼
Persist to etcd
Validating Webhook Example
yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: webapp-validator
webhooks:
- name: validate.webapp.example.com
clientConfig:
service:
name: webhook-service
namespace: webhook-system
path: /validate
caBundle: <base64-ca>
rules:
- operations: ["CREATE", "UPDATE"]
apiGroups: ["example.com"]
apiVersions: ["v1"]
resources: ["webapps"]
admissionReviewVersions: ["v1"]
sideEffects: None
failurePolicy: Fail
timeoutSeconds: 10
Mutating Webhook Example
yaml
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
name: webapp-mutator
webhooks:
- name: mutate.webapp.example.com
clientConfig:
service:
name: webhook-service
namespace: webhook-system
path: /mutate
caBundle: <base64-ca>
rules:
- operations: ["CREATE"]
apiGroups: ["example.com"]
apiVersions: ["v1"]
resources: ["webapps"]
admissionReviewVersions: ["v1"]
sideEffects: None
failurePolicy: Fail
timeoutSeconds: 10
ValidatingAdmissionPolicy (GA in 1.32)
Kubernetes now ships a built-in, in-process policy mechanism that needs no external webhook. ValidatingAdmissionPolicy reached GA in v1.30.
yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: require-labels
spec:
matchConstraints:
resourceRules:
- apiGroups: ["example.com"]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["webapps"]
validations:
- expression: "object.metadata.labels.exists(l, l == 'team')"
message: "All WebApps must have a 'team' label"
MutatingAdmissionPolicy (Beta in 1.33)
MutatingAdmissionPolicy entered beta in 1.33, enabling in-process mutation.
What Belongs Where in 2026
| Policy Type | Where to Put It |
| Required labels | ValidatingAdmissionPolicy (CEL) |
| Registry allowlists | ValidatingAdmissionPolicy (CEL) |
| Resource limits | ValidatingAdmissionPolicy (CEL) |
| Privileged container ban | ValidatingAdmissionPolicy (CEL) |
| Image signature verification | Validating Webhook (external lookup) |
| Sidecar injection | Mutating Webhook |
| Image digest pinning | Mutating Webhook |
The latency improvement of CEL-based policies is real: in-process CEL evaluation runs in microseconds versus tens of milliseconds for a webhook round trip, and you eliminate the webhook availability dependency.
Webhook Failure Policy
| Policy | Behavior | When to Use |
| Fail | Reject if webhook unreachable | Security-critical |
| Ignore | Allow if webhook unreachable | Optional features |
The Recovery Pattern
If a webhook is blocking cluster recovery:
bash
kubectl patch validatingwebhookconfiguration <name> --type='json' \
-p='[{"op":"replace","path":"/webhooks/0/failurePolicy","value":"Ignore"}]'
⚠️ This disables enforcement. Use only during confirmed outages.
6. Operator SDK and Kubebuilder
Kubebuilder and Operator SDK are the standard frameworks for building operators.
Kubebuilder Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ KUBEBUILDER ARCHITECTURE │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Generated Code │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │ API Types │ │ Controllers │ │ Config │ │ │
│ │ │ (CRD) │ │ (Reconcile) │ │ (Kustomize) │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ controller-runtime │ │
│ │ • Manager (lifecycle) │ │
│ │ • Client (CRUD) │ │
│ │ • Cache (Informer) │ │
│ │ • Webhook server │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ client-go │ │
│ │ • REST client │ │
│ │ • Informers │ │
│ │ • Workqueues │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Kubebuilder Workflow
bash
# 1. Initialize project
kubebuilder init --domain example.com --repo github.com/myorg/myoperator
# 2. Create API (CRD + Controller)
kubebuilder create api --group webapp --version v1 --kind WebApp
# 3. Define types in api/v1/webapp_types.go
# 4. Implement reconcile logic in controllers/webapp_controller.go
# 5. Generate CRDs
make manifests
# 6. Install CRDs
make install
# 7. Run controller locally
make run
# 8. Deploy to cluster
make docker-build docker-push IMG=myregistry/myoperator:v1
make deploy IMG=myregistry/myoperator:v1
The API Types
go
// api/v1/webapp_types.go
type WebAppSpec struct {
Image string `json:"image"`
Replicas int32 `json:"replicas,omitempty"`
Port int32 `json:"port,omitempty"`
}
type WebAppStatus struct {
AvailableReplicas int32 `json:"availableReplicas,omitempty"`
Conditions []metav1.Condition `json:"conditions,omitempty"`
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
type WebApp struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec WebAppSpec `json:"spec,omitempty"`
Status WebAppStatus `json:"status,omitempty"`
}
Kubebuilder Markers
| Marker | Purpose |
+kubebuilder:subresource:status | Enable status subresource |
+kubebuilder:subresource:scale | Enable scale subresource |
+kubebuilder:validation:Minimum=1 | Minimum value |
+kubebuilder:validation:Maximum=100 | Maximum value |
+kubebuilder:default=1 | Default value |
+kubebuilder:printcolumn | Additional printer columns |
+kubebuilder:webhook | Generate webhook config |
Operator SDK vs Kubebuilder
| Aspect | Operator SDK | Kubebuilder |
| Maintainer | Red Hat | Kubernetes SIG |
| Core | controller-runtime | controller-runtime |
| CLI | operator-sdk | kubebuilder |
| Scaffolding | More options | Simpler |
| OLM | Built-in | Add-on |
| Best For | Enterprise, OLM | General purpose |
Both frameworks use controller-runtime under the hood. The choice is mostly about tooling preference.
7. CRD Versioning and Conversion
CRDs support multiple versions, enabling safe API evolution.
Multiple Versions
yaml
spec:
versions:
- name: v1alpha1
served: true
storage: false
schema:
openAPIV3Schema: ...
- name: v1
served: true
storage: true # Only one storage version
schema:
openAPIV3Schema: ...
Storage vs Served Versions
| Setting | Meaning |
| served: true | API accepts this version |
| storage: true | Primary storage version (exactly one) |
Conversion Webhooks
When multiple versions exist, conversion webhooks convert between versions.
yaml
spec:
conversion:
strategy: Webhook
webhook:
clientConfig:
service:
name: webhook-service
namespace: webhook-system
path: /convert
conversionReviewVersions: ["v1"]
The Hub-and-Spoke Pattern
In conversion, one version is the hub (storage version), and others are spokes.
text
v1alpha1 ──► v1 (hub) ◄── v1beta1
Each spoke converts to/from the hub.
go
// Hub marks v1 as the hub
func (*WebApp) Hub() {}
// ConvertTo converts v1 to v1alpha1
func (src *WebApp) ConvertTo(dstRaw conversion.Hub) error {
dst := dstRaw.(*v1alpha1.WebApp)
// Conversion logic
return nil
}
// ConvertFrom converts v1alpha1 to v1
func (dst *WebApp) ConvertFrom(srcRaw conversion.Hub) error {
src := srcRaw.(*v1alpha1.WebApp)
// Conversion logic
return nil
}
CRD Versioning Best Practices
| Practice | Why |
| Start with v1alpha1 | Signal instability |
| Graduate to v1 | Stable API |
| Never change v1 schema | Compatibility |
| Use conversion webhooks | Multi-version support |
| Test conversion paths | Prevent data loss |
8. Finalizers and OwnerReferences
Finalizers
A finalizer is a marker that prevents an object from being deleted until cleanup is complete.
yaml
metadata:
finalizers:
- example.com/cleanup
Flow:
- User deletes object
- Object is marked
deletionTimestamp - Controller sees finalizer, performs cleanup
- Controller removes finalizer
- Object is deleted
go
const myFinalizer = "example.com/cleanup"
func (r *WebAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var webapp examplev1.WebApp
if err := r.Get(ctx, req.NamespacedName, &webapp); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
if webapp.DeletionTimestamp.IsZero() {
// Not being deleted — add finalizer if missing
if !controllerutil.ContainsFinalizer(&webapp, myFinalizer) {
controllerutil.AddFinalizer(&webapp, myFinalizer)
if err := r.Update(ctx, &webapp); err != nil {
return ctrl.Result{}, err
}
}
} else {
// Being deleted — run cleanup
if controllerutil.ContainsFinalizer(&webapp, myFinalizer) {
// Cleanup external resources
if err := r.cleanupExternal(&webapp); err != nil {
return ctrl.Result{}, err
}
controllerutil.RemoveFinalizer(&webapp, myFinalizer)
if err := r.Update(ctx, &webapp); err != nil {
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
return ctrl.Result{}, nil
}
OwnerReferences
OwnerReferences enable cascading deletion. When a parent is deleted, children are garbage collected.
yaml
metadata:
ownerReferences:
- apiVersion: example.com/v1
kind: WebApp
name: my-webapp
uid: <uid>
controller: true
blockOwnerDeletion: true
go
// Set owner reference
if err := ctrl.SetControllerReference(&webapp, &deployment, r.Scheme); err != nil {
return ctrl.Result{}, err
}
9. Server-Side Apply (SSA) for Operators
Server-Side Apply is the modern way for operators to manage resources.
Why SSA
| Client-Side Apply | Server-Side Apply |
| Uses last-applied annotation | Uses managedFields |
| Whole-resource conflicts | Field-level conflicts |
| Hard with multiple controllers | Natural multi-controller |
Using SSA in Operators
go
import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func (r *WebAppReconciler) applyDeployment(ctx context.Context, webapp *examplev1.WebApp) error {
deployment := &appsv1.Deployment{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "Deployment",
},
ObjectMeta: metav1.ObjectMeta{
Name: webapp.Name,
Namespace: webapp.Namespace,
},
Spec: r.deploymentSpec(webapp),
}
// Set owner reference
ctrl.SetControllerReference(webapp, deployment, r.Scheme)
// Server-Side Apply
return r.Patch(ctx, deployment, client.Apply, client.ForceOwnership, client.FieldOwner("webapp-controller"))
}
SSA Benefits for Operators
| Benefit | Why |
| Field ownership | Know which controller owns which field |
| Conflict detection | Detect when another controller modifies your fields |
| Multi-controller | Multiple controllers can manage the same resource |
| Idempotent | Apply is naturally idempotent |
10. Operator Lifecycle Manager (OLM)
OLM manages the lifecycle of operators in a cluster.
OLM Components
| Component | Purpose |
| OLM Operator | Manages CSV lifecycle |
| Catalog Operator | Resolves dependencies |
| CatalogSource | Source of operator bundles |
| Subscription | Request to install an operator |
| ClusterServiceVersion (CSV) | Operator metadata |
| InstallPlan | Step-by-step installation |
Installing an Operator with OLM
yaml
apiVersion: operators.coreos.com/v1alpha1
kind: Subscription
metadata:
name: my-operator
namespace: operators
spec:
channel: stable
name: my-operator
source: my-catalog
sourceNamespace: olm
OLM Benefits
| Benefit | Why |
| Dependency resolution | Automatically installs CRDs |
| Upgrades | Safe operator upgrades |
| Multi-tenancy | Operator scoping |
| Catalog | Discoverable operators |
11. Metrics, Logging, and Tracing for Operators
Prometheus Metrics
go
import (
"github.com/prometheus/client_golang/prometheus"
"sigs.k8s.io/controller-runtime/pkg/metrics"
)
var (
reconcileTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "webapp_reconcile_total",
Help: "Total number of reconciliations",
},
[]string{"result"},
)
reconcileDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "webapp_reconcile_duration_seconds",
Help: "Duration of reconciliations",
Buckets: prometheus.DefBuckets,
},
[]string{"result"},
)
)
func init() {
metrics.Registry.MustRegister(reconcileTotal, reconcileDuration)
}
Structured Logging
go
import "github.com/go-logr/logr"
func (r *WebAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx)
log.Info("Reconciling WebApp", "name", req.Name, "namespace", req.Namespace)
// ...
log.V(1).Info("Deployment created", "name", deployment.Name)
return ctrl.Result{}, nil
}
Distributed Tracing
go
import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
)
var tracer = otel.Tracer("webapp-controller")
func (r *WebAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
ctx, span := tracer.Start(ctx, "Reconcile")
defer span.End()
// ...
return ctrl.Result{}, nil
}
12. Testing Operators
The Testing Pyramid
| Level | Tool | Purpose |
| Unit | Go testing | Individual functions |
| Integration | envtest | Controller against real API server |
| E2E | KUTTL | Full cluster scenarios |
| Fuzzing | Go fuzzing | CRD input validation |
envtest
envtest starts a real API server and etcd for testing.
go
func TestReconcile(t *testing.T) {
// Setup envtest
testEnv := &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")},
}
cfg, err := testEnv.Start()
require.NoError(t, err)
defer testEnv.Stop()
// Create client
k8sClient, err := client.New(cfg, client.Options{Scheme: scheme})
require.NoError(t, err)
// Create reconciler
reconciler := &WebAppReconciler{
Client: k8sClient,
Scheme: k8sClient.Scheme(),
}
// Create test resource
webapp := &examplev1.WebApp{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "default",
},
Spec: examplev1.WebAppSpec{
Image: "nginx:1.25",
Replicas: 3,
},
}
require.NoError(t, k8sClient.Create(context.Background(), webapp))
// Reconcile
_, err = reconciler.Reconcile(context.Background(), ctrl.Request{
NamespacedName: types.NamespacedName{
Name: "test",
Namespace: "default",
},
})
require.NoError(t, err)
// Verify deployment created
var deployment appsv1.Deployment
err = k8sClient.Get(context.Background(), types.NamespacedName{
Name: "test",
Namespace: "default",
}, &deployment)
require.NoError(t, err)
assert.Equal(t, int32(3), *deployment.Spec.Replicas)
}
KUTTL
KUTTL (Kubernetes Test Tool) runs declarative E2E tests.
yaml
# kuttl-test.yaml
apiVersion: kuttl.dev/v1beta1
kind: TestSuite
testDirs:
- ./tests/e2e
yaml
# tests/e2e/webapp/00-create.yaml
apiVersion: example.com/v1
kind: WebApp
metadata:
name: test-webapp
spec:
image: nginx:1.25
replicas: 3
yaml
# tests/e2e/webapp/00-assert.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-webapp
spec:
replicas: 3
Fuzzing
Go fuzzing tests CRD input validation.
go
func FuzzWebAppSpec(f *testing.F) {
f.Add("nginx:1.25", int32(3), int32(8080))
f.Fuzz(func(t *testing.T, image string, replicas int32, port int32) {
spec := WebAppSpec{
Image: image,
Replicas: replicas,
Port: port,
}
// Validate spec
if err := spec.Validate(); err != nil {
// Expected for invalid input
}
})
}
13. Common Operators
Prometheus Operator
| CRD | Purpose |
| Prometheus | Prometheus instance |
| Alertmanager | Alertmanager instance |
| ServiceMonitor | Scrape configuration |
| PodMonitor | Pod scrape configuration |
| PrometheusRule | Alerting rules |
cert-manager
| CRD | Purpose |
| Certificate | TLS certificate request |
| Issuer | Namespace-scoped CA |
| ClusterIssuer | Cluster-scoped CA |
| CertificateRequest | Actual CSR |
Istio Operator
| CRD | Purpose |
| IstioOperator | Istio installation config |
| VirtualService | Traffic routing |
| DestinationRule | Load balancing |
| Gateway | Ingress/egress |
PART 3: PRODUCTION FAILURE MODES
14. Top 10 Extensibility Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | Webhook outage | API requests fail | Webhook down, failurePolicy: Fail | HA webhook, adjust policy |
| 2 | CRD version mismatch | Objects can't be read | Conversion webhook broken | Fix conversion logic |
| 3 | Controller crash loop | No reconciliation | Bug in Reconcile | Fix code, add retries |
| 4 | Finalizer stuck | Object can't be deleted | Cleanup fails | Remove finalizer manually |
| 5 | OwnerReference cycle | Garbage collection fails | Circular references | Fix ownership graph |
| 6 | Operator OOM | Controller killed | Memory leak | Increase limits, fix leak |
| 7 | CRD schema too strict | Valid objects rejected | Over-validation | Relax schema |
| 8 | Webhook timeout | Slow API calls | Webhook too slow | Optimize webhook |
| 9 | Operator RBAC insufficient | Permission denied | Missing permissions | Add RBAC rules |
| 10 | CRD storage version change | Data loss | Storage migration failure | Test migration |
15. Extensibility Debugging Runbook
"Operator is Broken" — Step-by-Step
text
STEP 1: Check operator pods
$ kubectl get pods -n <operator-namespace>
STEP 2: Check operator logs
$ kubectl logs -n <operator-namespace> <operator-pod>
$ kubectl logs -n <operator-namespace> <operator-pod> --previous
STEP 3: Check CRD status
$ kubectl get crd <crd-name>
$ kubectl describe crd <crd-name>
STEP 4: Check custom resources
$ kubectl get <plural> -A
$ kubectl describe <kind> <name>
STEP 5: Check webhooks
$ kubectl get validatingwebhookconfigurations
$ kubectl get mutatingwebhookconfigurations
$ kubectl describe validatingwebhookconfiguration <name>
STEP 6: Check webhook service
$ kubectl get svc -n <webhook-namespace> <webhook-service>
$ kubectl get endpoints -n <webhook-namespace> <webhook-service>
STEP 7: Check RBAC
$ kubectl auth can-i --list --as=system:serviceaccount:<ns>:<sa>
STEP 8: Check events
$ kubectl get events -A --sort-by=.metadata.creationTimestamp
STEP 9: Check conversion (if multi-version)
$ kubectl get crd <crd-name> -o yaml | grep -A10 conversion
STEP 10: Escalate
16. Blast Radius Analysis
What Happens When Extensibility Fails?
| Component | Impact | Severity |
| Validating webhook down (Fail) | All matching API requests fail | SEV-1 |
| Mutating webhook down (Fail) | All matching API requests fail | SEV-1 |
| Conversion webhook down | CRs with multiple versions fail | SEV-2 |
| Operator crash loop | No automation; existing resources remain | SEV-2 |
| CRD schema bug | Valid objects rejected | SEV-2 |
| Finalizer stuck | Resources can't be deleted | SEV-3 |
| Operator OOM | Controller killed | SEV-2 |
Mitigation Strategies
| Strategy | Implementation |
| HA webhooks | 3+ replicas, PDB |
| failurePolicy: Ignore | For non-critical webhooks |
| Operator resource limits | Prevent OOM |
| Conversion testing | Test all version paths |
| Finalizer timeout | Never block forever |
PART 4: CAPACITY PLANNING & COST MODELING
17. Operator Resource Overhead
Typical Operator Resource Usage
| Component | CPU Request | Memory Request | Replicas |
| controller-runtime | 100m | 128Mi | 1-3 |
| Webhook server | 100m | 128Mi | 3 (HA) |
| Prometheus Operator | 200m | 256Mi | 1 |
| cert-manager | 100m | 128Mi | 1 |
Sizing Formula
text
Operator CPU = (Reconcile rate × Reconcile cost) × Replicas
Operator Memory = (Cache size × Object count) + Code overhead
Example:
- 1,000 CRs
- 50 KB per CR in cache
- Memory = 1,000 × 50 KB + 128 MB = 178 MB
Webhook Capacity
| Webhook Type | Latency | Throughput |
| ValidatingAdmissionPolicy (CEL) | <1ms | Unlimited |
| Simple validating webhook | 5-20ms | ~500/s |
| Complex webhook | 50-200ms | ~50/s |
| Image verification | 100-500ms | ~20/s |
18. CRD Storage Impact on etcd
CRD Storage Considerations
| Factor | Impact |
| CR count | More objects = more storage |
| CR size | Status updates increase size |
| Version count | More versions = more storage |
| Update frequency | More writes = more etcd load |
etcd Capacity Planning
| CR Count | CR Size | Estimated Storage |
| 100 | 10 KB | 1 MB |
| 1,000 | 10 KB | 10 MB |
| 10,000 | 10 KB | 100 MB |
| 100,000 | 10 KB | 1 GB |
Production rule: Keep total etcd size under 2 GB. For large CR counts, consider aggregation or sharding.
19. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Operator SLA Design
| Target | Architecture |
| 99.9% | Single operator replica |
| 99.99% | 2+ replicas, leader election, HA webhooks |
| 99.999% | Above + chaos testing, multi-cluster |
Webhook HA Requirements
| Requirement | Why |
| 3+ replicas | Survive zone failure |
| PodDisruptionBudget | Prevent all replicas down |
| Pod anti-affinity | Spread across nodes |
| Service with local traffic | Reduce latency |
PART 5: ARCHITECTURE & STRATEGY
20. When to Build an Operator
Decision Framework
| Factor | Build Operator | Use Alternative |
| Complex stateful app | ✅ | — |
| Multi-step workflows | ✅ | — |
| Auto-remediation | ✅ | — |
| Simple stateless app | ❌ | Deployment |
| One-time setup | ❌ | Job |
| Configuration only | ❌ | ConfigMap + Reloader |
| Scheduled tasks | ❌ | CronJob |
The Operator Anti-Pattern
Operators carry real engineering costs in implementation, testing, maintenance, and a significantly expanded blast radius when things go wrong.
| Anti-Pattern | Why It's Bad |
| Operator for everything | Overhead, complexity |
| No testing | Bugs in production |
| No observability | Can't debug |
| cluster-admin RBAC | Security risk |
| No leader election | Split brain |
21. Operator Security Architecture
Least Privilege RBAC
yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: webapp-operator
rules:
- apiGroups: ["example.com"]
resources: ["webapps"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: [""]
resources: ["services"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
Security Checklist
| Practice | Why |
| Least privilege RBAC | Minimize blast radius |
| Non-root container | Security |
| Read-only rootfs | Immutability |
| seccomp RuntimeDefault | Syscall filtering |
| NetworkPolicy | Restrict traffic |
| Webhook TLS | Encrypted communication |
22. Compliance & Security for Extensibility
| Framework | Requirement |
| PCI-DSS | RBAC, audit logs, no privileged |
| HIPAA | Audit trails, access controls |
| SOC2 | Change management, monitoring |
| FedRAMP | FIPS 140-2, STIG |
PART 6: HANDS-ON LABS
Lab 1: Create a Basic CRD and Custom Resource
bash
# Create a CRD
cat <<'EOF' | kubectl apply -f -
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: webapps.example.com
spec:
group: example.com
names:
kind: WebApp
listKind: WebAppList
plural: webapps
singular: webapp
shortNames:
- wa
scope: Namespaced
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required:
- image
- replicas
properties:
image:
type: string
replicas:
type: integer
minimum: 1
maximum: 100
status:
type: object
properties:
availableReplicas:
type: integer
additionalPrinterColumns:
- name: Image
type: string
jsonPath: .spec.image
- name: Replicas
type: integer
jsonPath: .spec.replicas
subresources:
status: {}
EOF
# Create a custom resource
cat <<'EOF' | kubectl apply -f -
apiVersion: example.com/v1
kind: WebApp
metadata:
name: my-webapp
namespace: default
spec:
image: nginx:1.25
replicas: 3
EOF
# Verify
kubectl get crd webapps.example.com
kubectl get webapps
kubectl get wa
kubectl describe webapp my-webapp
Lab 2: Build a Minimal Controller with Kubebuilder
bash
# Install Kubebuilder
curl -L -o kubebuilder https://go.kubebuilder.io/dl/latest/$(go env GOOS)/$(go env GOARCH)
chmod +x kubebuilder && sudo mv kubebuilder /usr/local/bin/
# Initialize project
mkdir myoperator && cd myoperator
kubebuilder init --domain example.com --repo github.com/myorg/myoperator
# Create API
kubebuilder create api --group webapp --version v1 --kind WebApp
# Implement Reconcile (edit controllers/webapp_controller.go)
# ...
# Generate CRDs
make manifests
# Install CRDs
make install
# Run locally
make run
Lab 3: Implement a Validating Admission Webhook
go
// api/v1/webapp_webhook.go
package v1
import (
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/webhook"
)
func (r *WebApp) ValidateCreate() error {
if r.Spec.Replicas > 10 {
return fmt.Errorf("replicas must be ≤ 10, got %d", r.Spec.Replicas)
}
if r.Spec.Image == "" {
return fmt.Errorf("image is required")
}
return nil
}
func (r *WebApp) ValidateUpdate(old runtime.Object) error {
return r.ValidateCreate()
}
func (r *WebApp) ValidateDelete() error {
return nil
}
bash
# Generate webhook manifests
make manifests
# Deploy
make deploy IMG=myregistry/myoperator:v1
Lab 4: Implement a Mutating Admission Webhook
go
// api/v1/webapp_webhook.go
func (r *WebApp) Default() {
if r.Spec.Replicas == 0 {
r.Spec.Replicas = 1
}
if r.Spec.Port == 0 {
r.Spec.Port = 8080
}
}
bash
# Kubebuilder marker
//+kubebuilder:webhook:path=/mutate-webapp-example-com-v1-webapp,mutating=true,failurePolicy=fail,sideEffects=None,groups=example.com,resources=webapps,verbs=create;update,versions=v1,name=mwebapp.kb.io,admissionReviewVersions=v1
# Generate and deploy
make manifests
make deploy IMG=myregistry/myoperator:v1
Lab 5: Implement a Conversion Webhook
go
// api/v1/webapp_conversion.go
package v1
import (
"sigs.k8s.io/controller-runtime/pkg/conversion"
)
// Hub marks v1 as the hub
func (*WebApp) Hub() {}
// ConvertTo converts v1 to v1alpha1
func (src *WebApp) ConvertTo(dstRaw conversion.Hub) error {
dst := dstRaw.(*v1alpha1.WebApp)
dst.Spec.Image = src.Spec.Image
dst.Spec.Replicas = src.Spec.Replicas
dst.Spec.Port = src.Spec.Port
return nil
}
// ConvertFrom converts v1alpha1 to v1
func (dst *WebApp) ConvertFrom(srcRaw conversion.Hub) error {
src := srcRaw.(*v1alpha1.WebApp)
dst.Spec.Image = src.Spec.Image
dst.Spec.Replicas = src.Spec.Replicas
dst.Spec.Port = src.Spec.Port
return nil
}
Lab 6: Add Finalizers for External Cleanup
go
const myFinalizer = "example.com/cleanup"
func (r *WebAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var webapp examplev1.WebApp
if err := r.Get(ctx, req.NamespacedName, &webapp); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
if webapp.DeletionTimestamp.IsZero() {
if !controllerutil.ContainsFinalizer(&webapp, myFinalizer) {
controllerutil.AddFinalizer(&webapp, myFinalizer)
if err := r.Update(ctx, &webapp); err != nil {
return ctrl.Result{}, err
}
}
} else {
if controllerutil.ContainsFinalizer(&webapp, myFinalizer) {
if err := r.cleanupExternal(&webapp); err != nil {
return ctrl.Result{}, err
}
controllerutil.RemoveFinalizer(&webapp, myFinalizer)
if err := r.Update(ctx, &webapp); err != nil {
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
return ctrl.Result{}, nil
}
Lab 7: Test an Operator with envtest
go
func TestReconcile(t *testing.T) {
testEnv := &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")},
}
cfg, err := testEnv.Start()
require.NoError(t, err)
defer testEnv.Stop()
k8sClient, err := client.New(cfg, client.Options{Scheme: scheme})
require.NoError(t, err)
reconciler := &WebAppReconciler{
Client: k8sClient,
Scheme: k8sClient.Scheme(),
}
webapp := &examplev1.WebApp{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "default",
},
Spec: examplev1.WebAppSpec{
Image: "nginx:1.25",
Replicas: 3,
},
}
require.NoError(t, k8sClient.Create(context.Background(), webapp))
_, err = reconciler.Reconcile(context.Background(), ctrl.Request{
NamespacedName: types.NamespacedName{
Name: "test",
Namespace: "default",
},
})
require.NoError(t, err)
var deployment appsv1.Deployment
err = k8sClient.Get(context.Background(), types.NamespacedName{
Name: "test",
Namespace: "default",
}, &deployment)
require.NoError(t, err)
assert.Equal(t, int32(3), *deployment.Spec.Replicas)
}
Lab 8: Deploy an Operator with OLM
bash
# Install OLM
curl -sL https://github.com/operator-framework/operator-lifecycle-manager/releases/download/v0.28.0/install.sh | bash -s v0.28.0
# Create CatalogSource
cat <<'EOF' | kubectl apply -f -
apiVersion: operators.coreos.com/v1alpha1
kind: CatalogSource
metadata:
name: my-catalog
namespace: olm
spec:
sourceType: grpc
image: myregistry/myoperator-catalog:latest
displayName: My Operator Catalog
publisher: My Org
EOF
# Create Subscription
cat <<'EOF' | kubectl apply -f -
apiVersion: operators.coreors.com/v1alpha1
kind: Subscription
metadata:
name: my-operator
namespace: operators
spec:
channel: stable
name: my-operator
source: my-catalog
sourceNamespace: olm
EOF
# Check installation
kubectl get csv -n operators
kubectl get installplan -n operators
Lab 9: End-to-End Operator with Observability
go
// main.go
package main
import (
"flag"
"os"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"
)
func main() {
var metricsAddr string
var enableLeaderElection bool
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "leader-elect", false, "Enable leader election.")
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseDevMode(true)))
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
Metrics: server.Options{BindAddress: metricsAddr},
LeaderElection: enableLeaderElection,
LeaderElectionID: "webapp-operator-lock",
WebhookServer: webhook.NewServer(webhook.Options{Port: 9443}),
})
if err != nil {
os.Exit(1)
}
if err = (&WebAppReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
os.Exit(1)
}
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
os.Exit(1)
}
}
PART 7: INCIDENT MANAGEMENT
32. Operator Incident Post-Mortem Template
text
INCIDENT: Validating Webhook Outage - Cluster-Wide Deployment Failure
DATE: 2024-01-15
DURATION: 23 minutes
SEVERITY: SEV-1
IMPACT: All Pod creations failed. New deployments stuck.
TIMELINE:
14:00 - Deployment web:v2.0.0 started
14:01 - Alert: API server 500 errors
14:03 - Identified webhook service unavailable
14:05 - Webhook pods OOMKilled
14:08 - Increased webhook memory
14:12 - Webhook pods restarted
14:15 - API requests resumed
14:23 - Incident closed
ROOT CAUSE:
Webhook pod had 128Mi memory limit. High load caused OOM.
failurePolicy: Fail blocked all matching API requests.
LESSONS LEARNED:
1. Webhooks need HA and adequate resources.
2. failurePolicy: Fail can cause cluster-wide outages.
3. Use ValidatingAdmissionPolicy (CEL) for simple policies.
ACTION ITEMS:
[ ] Increase webhook resources (Owner: Platform)
[ ] Migrate simple policies to CEL (Owner: Platform)
[ ] Add webhook HA (Owner: Platform)
33. On-Call Runbook: Operator Failures
text
STEP 1: Check operator pods
$ kubectl get pods -n <operator-namespace>
STEP 2: Check operator logs
$ kubectl logs -n <operator-namespace> <operator-pod> --tail=100
STEP 3: Check CRD
$ kubectl get crd <crd-name>
$ kubectl describe crd <crd-name>
STEP 4: Check webhooks
$ kubectl get validatingwebhookconfigurations
$ kubectl get mutatingwebhookconfigurations
STEP 5: Check webhook service
$ kubectl get svc -n <webhook-namespace>
$ kubectl get endpoints -n <webhook-namespace>
STEP 6: Check RBAC
$ kubectl auth can-i --list --as=system:serviceaccount:<ns>:<sa>
STEP 7: If webhook blocking
# Temporarily set failurePolicy to Ignore
$ kubectl patch validatingwebhookconfiguration <name> --type='json' \
-p='[{"op":"replace","path":"/webhooks/0/failurePolicy","value":"Ignore"}]'
STEP 8: Escalate
34. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | Webhook blocking all API requests | 5 min | On-call + Platform + Management |
| SEV-2 | Operator crash loop / partial failure | 15 min | On-call + Platform |
| SEV-3 | Single CR stuck | 1 hour | On-call |
| SEV-4 | Configuration warning | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
35. Junior-Level Questions
| Question | Expected Answer |
| What is a CRD? | Custom Resource Definition — extends the API |
| What is a controller? | Control loop that reconciles desired vs actual state |
| What is an operator? | Controller with domain-specific knowledge |
| What is a webhook? | Admission callback |
| What is a finalizer? | Prevents deletion until cleanup |
36. Mid-Level Questions
| Question | Expected Answer |
| What is the watch-queue-reconcile pattern? | Informer → WorkQueue → Reconciler |
| What is the difference between validating and mutating webhooks? | Mutating modifies; validating allows/denies |
| What is the hub-and-spoke pattern? | One version is hub; others convert to/from it |
| What is Server-Side Apply? | Field-level ownership, managedFields |
| What is OLM? | Operator Lifecycle Manager |
37. Senior-Level Questions
| Question | Expected Answer |
| How do you make an operator idempotent? | Level-triggered, SSA, status subresource |
| How do you test an operator? | envtest, KUTTL, fuzzing |
| How do you handle CRD versioning? | Multiple versions, conversion webhook, hub-and-spoke |
| What is the webhook failure policy? | Fail (reject) or Ignore (allow) |
| When should you use CEL vs webhook? | CEL for in-process; webhook for external |
38. Staff/Principal Questions
| Question | Expected Answer |
| Design a multi-tenant operator platform. | OLM, RBAC, NetworkPolicy, resource quotas |
| How do you migrate CRD versions safely? | Test conversion, backup, rollback plan |
| How do you secure operators? | Least privilege RBAC, non-root, NetworkPolicy |
| How do you monitor operators? | Prometheus metrics, structured logs, tracing |
| When should you NOT build an operator? | Simple stateless apps, one-time setup |
Summary Cheat Sheet
| Concept | Key Takeaway |
| CRD | Custom Resource Definition — extends API |
| CR | Custom Resource — instance of a CRD |
| Controller | Watch-Queue-Reconcile loop |
| Informer | Watches API, caches, enqueues |
| WorkQueue | Rate-limited, deduplicated queue |
| Reconciler | Contains the control logic |
| Operator | Controller with domain knowledge |
| Admission Webhook | Intercepts API requests |
| Mutating Webhook | Modifies objects |
| Validating Webhook | Allows/denies |
| Conversion Webhook | Converts CRD versions |
| ValidatingAdmissionPolicy | CEL-based in-process policy (GA 1.32) |
| MutatingAdmissionPolicy | CEL-based in-process mutation (Beta 1.33) |
| Finalizer | Prevents deletion until cleanup |
| OwnerReference | Cascading deletion |
| Server-Side Apply | Field-level ownership |
| OLM | Operator Lifecycle Manager |
| Kubebuilder | Operator framework |
| envtest | Integration testing |
| KUTTL | E2E testing |
Stage 10: Autoscaling & Cost Optimization — The Comprehensive Guide
PART 1: CORE THEORY
1. The Kubernetes Cost Problem
Kubernetes is designed for availability, not cost efficiency. The default scheduler spreads pods across nodes to reduce blast radius when a node fails. This is a reasonable availability decision—and it directly conflicts with cost efficiency. The result: most clusters run at 20–30% actual utilization, meaning overprovisioning that costs three to five times the compute needed.
The Numbers
| Metric | Value | Source |
| Clusters over-provisioning CPU | 69% (up from 40% two years prior) | Cast AI 2026 State of Kubernetes report |
| Average CPU utilization | 8% | Cast AI 2026 |
| Container costs going to idle resources | 83% | Datadog |
| Mid-sized platform team waste | $45,000+ per month | Zesty |
Why Defaults Waste Money
| Default Behavior | Cost Impact |
| LeastAllocated scoring | Spreads pods, leaves nodes underutilized |
| Resource requests ignored | Scheduler uses requests, not actual usage |
| No consolidation | Idle nodes stay running |
| No spot integration | Pay full on-demand price |
| No cost visibility | Can't optimize what you can't see |
The Three Levers
| Lever | Tool | Impact |
| Rightsizing | VPA, Goldilocks | Match requests to actual usage |
| Scaling | HPA, KEDA | Match replicas to demand |
| Placement | Bin-packing, Karpenter | Pack workloads densely |
| Pricing | Spot instances | Pay less for the same compute |
2. Resource Requests and Limits
Resource management is the foundation of cost optimization. Getting it wrong causes both waste and reliability issues.
The Three Numbers
| Number | Meaning | Used By |
| Request | Minimum resources guaranteed | Scheduler |
| Limit | Maximum resources allowed | Kernel (cgroups) |
| Actual usage | What the workload really consumes | Monitoring |
The gap between these three numbers is where cost and reliability problems show up.
The Cost Impact
| Scenario | Request | Actual | Waste |
| Over-requested | 2 CPU | 200m | 90% waste |
| Under-requested | 100m | 500m | Throttling, OOMKills |
| Right-sized | 300m | 250m | Minimal waste |
The Scheduler's Perspective
The scheduler operates on requests, not actual usage. A Pod requesting 2 CPUs but using 200m is treated as a 2-CPU Pod during scheduling. A cluster with 8% actual CPU utilization can still appear “busy” to the autoscaler because inflated resource requests look like real demand.
QoS Classes and Cost
| QoS | Requests vs Limits | Eviction Priority | Cost |
| Guaranteed | requests == limits | Last | Highest |
| Burstable | requests < limits | Middle | Medium |
| BestEffort | No requests/limits | First | Lowest |
3. Horizontal Pod Autoscaler
The Horizontal Pod Autoscaler (HPA) scales the number of Pod replicas based on observed metrics.
How HPA Works
text
HPA Controller (every 15s)
│
▼
Read metrics (CPU, memory, custom)
│
▼
Calculate desired replicas:
desiredReplicas = ceil(currentReplicas × (currentMetric / targetMetric))
│
▼
Scale Deployment/ReplicaSet
HPA Example
yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 15
- type: Pods
value: 4
periodSeconds: 15
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 25
periodSeconds: 60
HPA Best Practices 2026
| Practice | Why |
| Set appropriate stabilization windows | Prevent thrashing |
| Use behavior policies | Control scale-up/down speed |
| Combine with VPA for right-sized pods | Ensure requests are accurate |
| Monitor HPA decisions | kubectl describe hpa |
The Behavior Block
The behavior block is critical for production. A common pattern: scale up fast (100% in 15 seconds) and scale down slowly (25% per minute with a 5-minute stabilization window).
HPA Limitations
| Limitation | Impact |
| CPU-based only (default) | Doesn't work for queue-based workloads |
| Reacts to metrics | 15-second interval; not instantaneous |
| No scale-to-zero | Minimum replicas must be ≥ 1 |
| Conflicts with VPA | If both use CPU metrics |
4. Vertical Pod Autoscaler
The Vertical Pod Autoscaler (VPA) adjusts the CPU and memory requests/limits of Pods.
How VPA Works
text
VPA Recommender
│
▼
Analyze historical usage
│
▼
Generate recommendations (lower, target, upper)
│
▼
VPA Updater (if Auto mode)
│
▼
Evict and recreate Pods with new requests
VPA Example
yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: web-vpa
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: web
updatePolicy:
updateMode: "Auto" # Off, Initial, Auto
resourcePolicy:
containerPolicies:
- containerName: '*'
minAllowed:
cpu: 100m
memory: 128Mi
maxAllowed:
cpu: 4
memory: 8Gi
VPA Update Modes
| Mode | Behavior |
| Off | Recommendations only (no changes) |
| Initial | Set requests on Pod creation |
| Auto | Evict and recreate Pods to apply |
VPA Best Practices
| Practice | Why |
| Run in recommendation mode for 7 days | Get accurate data |
| Never run VPA Auto alongside HPA on the same CPU metric | They will fight each other |
| Use VPA for memory right-sizing | Memory is less variable than CPU |
| Set min/max bounds | Prevent extreme recommendations |
The VPA + HPA Conflict
HPA and VPA conflict when resource requests change, creating unstable replica counts and the Kubernetes “death spiral”. VPA’s histograms get polluted when HPA scales.
Solution: Use VPA for memory only, HPA for CPU. Or use VPA in recommendation mode only.
PART 2: ADVANCED CONCEPTS
5. KEDA
KEDA (Kubernetes Event-Driven Autoscaling) scales workloads based on external events — message queues, databases, HTTP endpoints — rather than just CPU/memory.
Why KEDA
Traditional HPA based on CPU and memory may respond too slowly for event-driven workloads such as offline jobs and streaming data. KEDA monitors event backlogs from sources such as message queues and databases, creates Jobs or Deployment replicas within seconds, and scales down to zero after tasks complete.
KEDA Architecture
text
Event Source (Kafka, RabbitMQ, SQS)
│
▼
KEDA Scaler (periodic queries)
│
▼
KEDA Operator
│
▼
HPA (managed by KEDA)
│
▼
Deployment / Job (scale replicas)
KEDA Example (ScaledObject)
yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: kafka-consumer
spec:
scaleTargetRef:
name: kafka-consumer
minReplicaCount: 0 # Scale to zero!
maxReplicaCount: 30
triggers:
- type: kafka
metadata:
bootstrapServers: kafka:9092
consumerGroup: my-group
topic: orders
lagThreshold: "100"
KEDA Example (ScaledJob)
yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledJob
metadata:
name: video-transcoder
spec:
jobTargetRef:
template:
spec:
containers:
- name: transcoder
image: transcoder:1.0
triggers:
- type: rabbitmq
metadata:
protocol: amqp
queueName: video-jobs
mode: QueueLength
value: "5"
maxReplicaCount: 10
ScaledJob vs ScaledObject
| Aspect | ScaledObject | ScaledJob |
| Target | Deployment/StatefulSet | Job |
| Use case | Continuous throughput | Discrete tasks |
| Scale to zero | ✅ | ✅ (after completion) |
| Concurrency | Pool of replicas | One Job per event |
Use ScaledJob when each event maps to a discrete, long-running task that runs to completion in its own pod. Use ScaledObject when events drive continuous throughput.
Supported Event Sources
| Category | Sources |
| Message Queues | Kafka, RabbitMQ, SQS, Azure Service Bus |
| Databases | PostgreSQL, MySQL, MongoDB |
| Cloud | AWS CloudWatch, Azure Monitor, GCP Pub/Sub |
| HTTP | HTTP endpoints |
| Metrics | Prometheus, Datadog |
6. Cluster Autoscaler
The Cluster Autoscaler (CAS) scales the number of nodes in pre-defined node groups.
How CAS Works
CAS polls the Kubernetes API every 10 seconds. When it finds pods in a Pending state, it identifies which node group could accommodate them and triggers a scale-up event. The scale-up request goes to the cloud provider’s abstraction layer: an Auto Scaling Group on AWS, a Managed Instance Group on GCP, or a Virtual Machine Scale Set on Azure. The cloud provider spins up a node, Kubernetes registers it, and the scheduler places the pods. This roundtrip typically takes 3–4 minutes.
CAS Example
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: cluster-autoscaler
namespace: kube-system
spec:
replicas: 1
selector:
matchLabels:
app: cluster-autoscaler
template:
metadata:
labels:
app: cluster-autoscaler
spec:
serviceAccountName: cluster-autoscaler
containers:
- image: registry.k8s.io/autoscaling/cluster-autoscaler:v1.32.0
name: cluster-autoscaler
command:
- ./cluster-autoscaler
- --v=4
- --cloud-provider=aws
- --skip-nodes-with-local-storage=false
- --expander=least-waste
- --node-group-auto-discovery=asg:tag=k8s.io/cluster-autoscaler/enabled
CAS Limitations
| Limitation | Impact |
| Node groups | Pre-defined instance types only |
| Slow scale-up | 3–4 minutes |
| No repacking | Doesn’t consolidate existing workloads |
| Request-based | Inflated requests look like real demand |
| GKE only option | On GKE, CAS is still the only production option |
7. Karpenter
Karpenter is the modern alternative to Cluster Autoscaler. It provisions cloud instances directly — no node groups, no intermediary ASG call, just a direct API request for the optimal instance type selected at scheduling time.
Karpenter vs Cluster Autoscaler
| Dimension | Karpenter | Cluster Autoscaler |
| Provisioning | 45–60 seconds | 3–4 minutes |
| Instance selection | Any type (cheapest fitting) | Pre-defined node groups |
| Consolidation | ✅ Active repacking | ❌ Does not repack |
| Spot support | Native, automatic fallback | Separate ASGs, manual |
| GKE support | ❌ No official provider | ✅ Only option |
| AWS EKS | Default engine in EKS Auto Mode | Legacy |
| Azure AKS | GA in early 2026 | Legacy |
How Karpenter Works
text
Unschedulable Pod
│
▼
Karpenter Controller (watches for pending pods)
│
▼
Calculate optimal instance type (any type, cheapest)
│
▼
Call cloud API directly (no ASG)
│
▼
Node provisioned in 45-60 seconds
│
▼
Pod scheduled
Karpenter NodePool Example
yaml
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: default
spec:
template:
spec:
requirements:
- key: kubernetes.io/arch
operator: In
values: ["amd64"]
- key: karpenter.sh/capacity-type
operator: In
values: ["spot", "on-demand"]
- key: karpenter.k8s.aws/instance-family
operator: In
values: ["t3", "t3a", "t2"]
nodeClassRef:
name: default
limits:
cpu: 1000
memory: 1000Gi
disruption:
consolidationPolicy: WhenUnderutilized
expireAfter: 720h
The Consolidation Advantage
Karpenter actively consolidates running workloads onto fewer nodes. It identifies underutilized nodes, drains them, and deletes them — reducing node count without manual intervention. Cast AI Evictor cut node count by 50% in one measured case, keeping remaining nodes at 80% CPU utilization.
8. Spot Instances
Spot instances offer 60–90% discounts over on-demand instances. Cloud providers sell unused capacity at reduced rates with the caveat that instances can be reclaimed with short notice.
Spot Interruption Notice
| Cloud | Notice Period |
| AWS | 2 minutes |
| Azure | 30 seconds |
| GCP | 30 seconds |
The Golden Rule
Treat spot instances as ephemeral. Assume any spot instance can disappear at any moment. Design your architecture accordingly with automatic recovery and multi-instance redundancy.
Workload Classification
| Spot-Safe | Avoid Spot |
| Stateless web services | Single-instance databases |
| Batch processing jobs | Stateful apps without replication |
| CI/CD build agents | Real-time processing |
| Dev/test environments | Long-running tasks without checkpointing |
Spot Node Pool Example (AWS EKS)
yaml
apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig
metadata:
name: production-cluster
region: us-east-1
managedNodeGroups:
- name: spot-workers
instanceTypes:
- t3.large
- t3a.large
- t2.large
spot: true
minSize: 3
maxSize: 20
desiredCapacity: 5
labels:
node-lifecycle: spot
taints:
- key: spot-instance
value: "true"
effect: NoSchedule
Pod Tolerations for Spot
yaml
spec:
tolerations:
- key: spot-instance
operator: Equal
value: "true"
effect: NoSchedule
Spot Best Practices
| Practice | Why |
| Diversify instance types | Reduces interruption frequency |
| Use multiple AZs | Capacity is regional |
| Set PDBs | Ensure availability during interruptions |
| Graceful shutdown | Handle 2-minute termination notice |
| Mix on-demand + spot | Fallback for critical workloads |
9. Bin-Packing and Node Consolidation
Bin-packing places pods densely on fewer nodes, reducing idle node cost.
Why the Default Scheduler Doesn't Pack
The default scoring plugin is NodeResourcesFit with a LeastAllocated strategy. This scores nodes higher when they have more free capacity, spreading pods thin across many nodes each running at low utilization.
Switching to MostAllocated
yaml
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: default-scheduler
pluginConfig:
- name: NodeResourcesFit
args:
scoringStrategy:
type: MostAllocated
resources:
- name: cpu
weight: 1
- name: memory
weight: 1
The Two Layers
| Layer | What It Does | When It Happens |
| Bin-packing | Scheduling decision | Pod placement time |
| Consolidation | Removes idle nodes | Ongoing |
Both layers are necessary for sustained cost reduction.
The Consolidation Engines
| Engine | How It Works |
| Karpenter | Active consolidation, direct cloud API |
| Cast AI Evictor | Evicts pods from underutilized nodes |
| Descheduler | Evicts pods violating policies |
10. Cost Monitoring Tools
Kubecost vs OpenCost
| Aspect | Kubecost | OpenCost |
| Launched | 2019 | 2022 |
| Acquired by | IBM (2024) | CNCF sandbox |
| Cost allocation | Any K8s concept | Any K8s concept |
| Multi-cluster | ✅ Yes | ✅ Yes |
| Cloud integration | AWS, Azure, GCP | AWS, Azure, GCP |
| Pricing | Freemium + Enterprise | Free |
| Best for | Enterprise cost management | Open-source cost visibility |
What Cost Tools Provide
| Feature | Description |
| Cost allocation | By namespace, deployment, label, team |
| Real-time monitoring | In-cluster + cloud costs |
| Optimization recommendations | Rightsizing, waste detection |
| Anomaly detection | Alert on spend spikes |
| Multi-cluster | Unified view |
Installing Kubecost
bash
helm repo add kubecost https://kubecost.github.io/cost-analyzer/
helm install kubecost kubecost/cost-analyzer \
--namespace kubecost --create-namespace \
--set kubecostToken="<token>"
11. Rightsizing and Goldilocks
Goldilocks is a tool that provides VPA recommendations in a dashboard.
How Goldilocks Works
- Deploys VPA in recommendation mode for all workloads
- Provides a dashboard showing recommendations
- Helps teams right-size without manual analysis
Goldilocks Architecture
text
Goldilocks Controller
│
▼
Creates VPA objects for each workload
│
▼
VPA Recommender generates recommendations
│
▼
Goldilocks Dashboard shows recommendations
Installing Goldilocks
bash
helm repo add fairwinds-stable https://charts.fairwinds.com/stable
helm install goldilocks fairwinds-stable/goldilocks \
--namespace goldilocks --create-namespace
12. HPA + VPA + KEDA Coordination
The three autoscalers must work together, not against each other.
The Coordination Matrix
| Combination | Safe? | Notes |
| HPA (CPU) + VPA (memory) | ✅ | Different resources |
| HPA (CPU) + VPA (Auto) | ❌ | They fight |
| HPA (CPU) + VPA (Off) | ✅ | Recommendations only |
| KEDA + HPA | ✅ | KEDA manages HPA |
| KEDA + VPA | ✅ | Different scaling dimensions |
The Recommended Architecture
text
HPA → scales replicas based on CPU/custom metrics
VPA (Off) → recommends requests for right-sizing
KEDA → scales based on external events (queues, databases)
Karpenter → provisions nodes for unschedulable pods
The Death Spiral
When HPA and VPA both act on CPU:
- HPA scales up → more replicas
- VPA sees lower per-pod usage → reduces requests
- HPA sees higher utilization → scales up more
- Repeat → unstable replica count
Prevention: Never run VPA Auto alongside HPA on the same CPU metric.
13. Cluster Proportional Autoscaler
The Cluster Proportional Autoscaler (CPA) scales workloads proportionally to cluster size (number of nodes or cores).
When to Use CPA
| Use Case | Example |
| DNS scaling | CoreDNS replicas scale with nodes |
| Ingress scaling | NGINX replicas scale with nodes |
| Monitoring | Prometheus replicas scale with nodes |
CPA Example
yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: coredns
namespace: kube-system
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: coredns
minReplicas: 2
maxReplicas: 10
metrics:
- type: External
external:
metric:
name: cluster_cores
target:
type: AverageValue
averageValue: "256"
PART 3: PRODUCTION FAILURE MODES
14. Top 10 Autoscaling & Cost Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | PDB blocks scale-down | Nodes never removed | PDB prevents eviction | Adjust PDB |
| 2 | HPA/VPA conflict | Unstable replicas | Both scale on CPU | Separate metrics |
| 3 | Inflated requests | Cluster appears busy | Requests >> usage | VPA rightsizing |
| 4 | Karpenter consolidation storm | Constant node churn | Consolidation too aggressive | Tune consolidation policy |
| 5 | Spot interruption cascade | Multiple pods evicted | All replicas on same spot pool | Diversify, PDB |
| 6 | HPA metric unavailable | HPA doesn't scale | Custom metrics API down | Fix metrics adapter |
| 7 | KEDA scaler misconfiguration | Scale to zero unexpectedly | Wrong metric threshold | Tune scaler |
| 8 | Cluster Autoscaler slow | Pods Pending for minutes | 3-4 minute provisioning | Migrate to Karpenter |
| 9 | Cost anomaly | Unexpected bill spike | Runaway workload, no limits | Set limits, alerts |
| 10 | Bin-packing breaks HA | Single node failure kills service | Over-consolidation | Pod anti-affinity |
The PDB Deadlock (Real Production Lesson)
A PDB defines how many pods must remain available during voluntary disruptions. In one production case, CPU utilization across nodes was very low, but the cluster was not scaling down. The PDB configuration prevented Kubernetes from evicting the pods. Because the pods could not be evicted, the autoscaler was not allowed to remove the node. This type of configuration issue can cause nodes that never scale down, wasted compute resources, and significantly increased cloud costs in large clusters.
15. Autoscaling Debugging Runbook
“HPA isn’t scaling” — Step-by-Step
text
STEP 1: Check HPA status
$ kubectl get hpa
$ kubectl describe hpa <name>
# Look at current metrics, desired replicas, conditions
STEP 2: Check metrics availability
$ kubectl top pods
$ kubectl get --raw /apis/metrics.k8s.io/v1beta1/nodes
# If empty, metrics-server is down
STEP 3: Check resource requests
$ kubectl get deployment <name> -o jsonpath='{.spec.template.spec.containers[*].resources.requests}'
# HPA uses requests for CPU utilization %
STEP 4: Check HPA events
$ kubectl get events --field-selector involvedObject.name=<hpa-name>
STEP 5: Check custom metrics (if used)
$ kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1
STEP 6: Check behavior policies
$ kubectl get hpa <name> -o yaml | grep -A20 behavior
# Stabilization windows may be blocking
STEP 7: Escalate
“Cluster isn’t scaling down” — Step-by-Step
text
STEP 1: Check node utilization
$ kubectl top nodes
STEP 2: Check PDBs
$ kubectl get pdb -A
$ kubectl describe pdb <name>
# PDB may be blocking eviction
STEP 3: Check Cluster Autoscaler logs
$ kubectl logs -n kube-system -l app=cluster-autoscaler --tail=100
STEP 4: Check Karpenter logs (if using Karpenter)
$ kubectl logs -n karpenter -l app.kubernetes.io/name=karpenter --tail=100
STEP 5: Check for pods that can't be evicted
$ kubectl get pods -A --field-selector status.phase=Running
# Look for pods without controllers (bare pods)
STEP 6: Check node annotations
$ kubectl describe node <node> | grep -A5 "Annotations"
STEP 7: Escalate
16. Blast Radius Analysis
What Happens When Autoscaling Fails?
| Component | Impact | Severity |
| HPA down | No replica scaling; capacity fixed | SEV-2 |
| VPA down | No rightsizing | SEV-3 |
| KEDA down | No event-driven scaling | SEV-2 |
| Karpenter down | No node provisioning | SEV-1 |
| Cluster Autoscaler down | No node scaling | SEV-1 |
| Cost monitoring down | No visibility | SEV-3 |
| PDB blocking scale-down | Wasted cost | SEV-3 |
Mitigation Strategies
| Strategy | Implementation |
| HA autoscalers | Multiple replicas |
| Fallback | On-demand node groups |
| Monitoring | Alerts on scaling events |
| Cost alerts | Budget alerts |
| Testing | Chaos engineering for scaling |
PART 4: CAPACITY PLANNING & COST MODELING
17. Cost Modeling and FinOps
The FinOps Lifecycle
| Phase | Activities |
| Inform | Cost visibility, allocation, showback |
| Optimize | Rightsizing, spot, bin-packing |
| Operate | Governance, budgets, alerts |
Cost Allocation Dimensions
| Dimension | Example |
| Namespace | team-a, team-b |
| Label | app=web, env=prod |
| Deployment | web, api, db |
| Cluster | prod-us-east, prod-eu-west |
The Optimization Formula
text
Savings = (Current cost) - (Optimized cost)
Optimized cost = (Rightsized resources × Correct price) × (1 - Spot discount)
Example:
Current: 100 nodes × $0.20/hour = $20/hour
Rightsized: 60 nodes
Spot: 40% of nodes at 70% discount
Optimized: (60 × $0.20 × 0.6) + (60 × $0.20 × 0.4 × 0.3) = $8.64/hour
Savings: 57%
18. Optimization ROI Calculation
The ROI of Autoscaling
| Optimization | Typical Savings | Effort |
| Rightsizing (VPA) | 20–40% | Low |
| Spot instances | 60–90% on eligible workloads | Medium |
| Bin-packing | 20–30% | Medium |
| Karpenter consolidation | 30–50% | Medium |
| KEDA scale-to-zero | 50–80% on batch | Medium |
| Combined | 50–70% | High |
Case Study: Cast AI Evictor
“Cast AI Evictor cut node count by 50% in one measured case, keeping remaining nodes at 80% CPU utilization.”
19. SLA & Availability Design for Autoscaling
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Autoscaling SLA Design
| Target | Architecture |
| 99.9% | HPA with 2+ replicas, basic monitoring |
| 99.99% | HPA + VPA (Off) + PDBs + Karpenter |
| 99.999% | Full stack: HPA + KEDA + Karpenter + Spot with fallback + chaos-tested |
The Availability vs Cost Trade-Off
| Strategy | Availability | Cost |
| On-demand only | Highest | Highest |
| Mixed spot + on-demand | High | Medium |
| Spot only | Medium | Lowest |
| Bin-packed | Lower (blast radius) | Lowest |
PART 5: ARCHITECTURE & STRATEGY
20. Cost Governance Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ COST GOVERNANCE STACK │
│ │
│ Layer 1: Visibility │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Kubecost / OpenCost │ │
│ │ • Cost allocation by namespace, label, team │ │
│ │ • Real-time monitoring │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 2: Optimization │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ VPA (Off) + Goldilocks │ │
│ │ • Rightsizing recommendations │ │
│ │ • Historical analysis │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 3: Scaling │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ HPA + KEDA + Karpenter │ │
│ │ • Replica scaling (HPA/KEDA) │ │
│ │ • Node scaling (Karpenter) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 4: Governance │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ ResourceQuotas + LimitRanges + Budgets │ │
│ │ • Team budgets │ │
│ │ • Resource caps │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
21. Multi-Tenant Cost Allocation
Showback vs Chargeback
| Model | Description | Impact |
| Showback | Show teams their costs | Awareness |
| Chargeback | Charge teams for costs | Accountability |
Cost Allocation Labels
yaml
metadata:
labels:
team: platform
cost-center: engineering
environment: production
app: web
ResourceQuotas for Cost Control
yaml
apiVersion: v1
kind: ResourceQuota
metadata:
name: team-budget
namespace: team-a
spec:
hard:
requests.cpu: "100"
requests.memory: 200Gi
limits.cpu: "200"
limits.memory: 400Gi
22. Compliance & Security for Cost Management
| Framework | Requirement |
| SOC2 | Change management, monitoring |
| PCI-DSS | Access controls, audit logs |
| HIPAA | Audit trails, access controls |
| FedRAMP | FIPS 140-2, cost controls |
PART 6: HANDS-ON LABS
Lab 1: Configure HPA with CPU Metrics
bash
# Deploy a workload
kubectl create deployment web --image=nginx:1.25-alpine --replicas=2
# Set resource requests
kubectl set resources deployment web --requests=cpu=100m,memory=128Mi
# Create HPA
kubectl autoscale deployment web --min=2 --max=10 --cpu-percent=70
# Verify
kubectl get hpa
kubectl describe hpa web
# Generate load
kubectl run load --image=busybox --restart=Never -- \
sh -c "while true; do wget -q -O- http://web; done"
# Watch scaling
kubectl get hpa web -w
# Cleanup
kubectl delete pod load
kubectl delete hpa web
kubectl delete deployment web
Lab 2: Tune HPA Behavior Policies
bash
kubectl create deployment web --image=nginx:1.25-alpine --replicas=2
kubectl set resources deployment web --requests=cpu=100m
cat <<'EOF' | kubectl apply -f -
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 15
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 25
periodSeconds: 60
EOF
# Test
kubectl get hpa web-hpa -w
# Cleanup
kubectl delete hpa web-hpa
kubectl delete deployment web
Lab 3: VPA in Recommendation Mode
bash
# Install VPA
kubectl apply -f https://github.com/kubernetes/autoscaler/raw/master/vertical-pod-autoscaler/deploy/vpa-v1-crd-gen.yaml
# Deploy a workload
kubectl create deployment web --image=nginx:1.25-alpine
# Create VPA
cat <<'EOF' | kubectl apply -f -
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: web-vpa
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: web
updatePolicy:
updateMode: "Off"
EOF
# Wait for recommendations
sleep 60
kubectl describe vpa web-vpa
# Look at Recommendation section
# Cleanup
kubectl delete vpa web-vpa
kubectl delete deployment web
Lab 4: KEDA with a Message Queue
Prerequisites: KEDA installed, a message queue (RabbitMQ, Kafka) available.
bash
# Install KEDA
helm repo add kedacore https://kedacore.github.io/charts
helm install keda kedacore/keda -n keda --create-namespace
# Deploy a consumer
kubectl create deployment consumer --image=myconsumer:1.0
# Create ScaledObject
cat <<'EOF' | kubectl apply -f -
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: consumer-scaler
spec:
scaleTargetRef:
name: consumer
minReplicaCount: 0
maxReplicaCount: 20
triggers:
- type: rabbitmq
metadata:
protocol: amqp
queueName: orders
mode: QueueLength
value: "5"
authenticationRef:
name: rabbitmq-auth
EOF
# Watch scaling
kubectl get hpa -w
# Cleanup
kubectl delete scaledobject consumer-scaler
kubectl delete deployment consumer
Lab 5: Deploy Karpenter and Observe Consolidation
Prerequisites: AWS EKS cluster, Karpenter installed.
bash
# Create a NodePool
cat <<'EOF' | kubectl apply -f -
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: default
spec:
template:
spec:
requirements:
- key: karpenter.sh/capacity-type
operator: In
values: ["spot", "on-demand"]
- key: karpenter.k8s.aws/instance-family
operator: In
values: ["t3", "t3a", "t2"]
limits:
cpu: 100
memory: 100Gi
disruption:
consolidationPolicy: WhenUnderutilized
expireAfter: 720h
EOF
# Deploy workloads
kubectl create deployment web --image=nginx --replicas=5
# Watch nodes
kubectl get nodes -w
# Scale down and observe consolidation
kubectl scale deployment web --replicas=1
kubectl get nodes -w
# Karpenter should consolidate
# Cleanup
kubectl delete deployment web
kubectl delete nodepool default
Lab 6: Spot Instance Node Pool with Fallback
yaml
# NodePool with spot priority and on-demand fallback
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: spot-first
spec:
template:
spec:
requirements:
- key: karpenter.sh/capacity-type
operator: In
values: ["spot", "on-demand"]
- key: karpenter.k8s.aws/instance-family
operator: In
values: ["t3", "t3a", "m5", "m5a"]
limits:
cpu: 200
memory: 400Gi
disruption:
consolidationPolicy: WhenUnderutilized
yaml
# Workload with spot toleration
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 10
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
tolerations:
- key: karpenter.sh/capacity-type
operator: Equal
value: "spot"
effect: NoSchedule
containers:
- name: web
image: nginx:1.25-alpine
Lab 7: Bin-Packing with MostAllocated Scoring
bash
# Patch the scheduler config (on control plane node)
sudo tee /etc/kubernetes/scheduler-config.yaml <<'EOF'
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: default-scheduler
pluginConfig:
- name: NodeResourcesFit
args:
scoringStrategy:
type: MostAllocated
resources:
- name: cpu
weight: 1
- name: memory
weight: 1
EOF
# Update kube-scheduler static pod to use --config
# (Edit /etc/kubernetes/manifests/kube-scheduler.yaml)
# Test
kubectl create deployment web --image=nginx --replicas=10
kubectl get pods -o wide
# Pods should pack onto fewer nodes
# Cleanup
kubectl delete deployment web
Lab 8: Install Kubecost and Analyze Costs
bash
# Install Kubecost
helm repo add kubecost https://kubecost.github.io/cost-analyzer/
helm install kubecost kubecost/cost-analyzer \
--namespace kubecost --create-namespace
# Port-forward the dashboard
kubectl port-forward -n kubecost svc/kubecost-cost-analyzer 9090:9090
# Open http://localhost:9090
# Analyze:
# - Cost by namespace
# - Cost by deployment
# - Savings opportunities
# - Idle resources
# Cleanup
helm uninstall kubecost -n kubecost
kubectl delete namespace kubecost
Lab 9: End-to-End Cost Optimization
bash
kubectl create namespace cost-lab
# Deploy with right-sized requests
kubectl create deployment web --image=nginx:1.25-alpine -n cost-lab --replicas=2
kubectl set resources deployment web -n cost-lab \
--requests=cpu=100m,memory=128Mi \
--limits=cpu=500m,memory=256Mi
# HPA
cat <<'EOF' | kubectl apply -n cost-lab -f -
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
EOF
# PDB
cat <<'EOF' | kubectl apply -n cost-lab -f -
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: web-pdb
spec:
minAvailable: 1
selector:
matchLabels:
app: web
EOF
# Verify
kubectl get all,hpa,pdb -n cost-lab
# Cleanup
kubectl delete namespace cost-lab
PART 7: INCIDENT MANAGEMENT
32. Cost Incident Post-Mortem Template
text
INCIDENT: Cost Spike - Unexpected 300% Increase in Monthly Bill
DATE: 2024-01-15
DURATION: 5 days
SEVERITY: SEV-2
IMPACT: Cloud bill increased from $15,000 to $60,000.
TIMELINE:
Day 1: Batch job deployed without resource limits
Day 3: Batch job scaled to 50 replicas (HPA)
Day 5: Cost alert fired
Day 5: On-call investigated, identified runaway batch job
Day 5: Job deleted, limits applied
Day 6: Cost normalized
ROOT CAUSE:
Batch job had no CPU limits and HPA scaled it to 50 replicas.
Each replica requested 2 CPUs, consuming 100 CPUs total.
No cost alerts for 5 days.
LESSONS LEARNED:
1. All workloads must have resource limits.
2. Cost alerts must fire at 50% of budget.
3. HPA maxReplicas must be bounded.
ACTION ITEMS:
[ ] Enforce resource limits via LimitRange (Owner: Platform)
[ ] Add cost alerts at 50% of monthly budget (Owner: SRE)
[ ] Audit all workloads for missing limits (Owner: Platform)
33. On-Call Runbook: Cost Spike / Autoscaling Failure
text
STEP 1: Check cost dashboard
# Open Kubecost/OpenCost dashboard
STEP 2: Identify the spike source
# By namespace, deployment, label
STEP 3: Check for runaway workloads
$ kubectl get pods -A --field-selector status.phase=Running
$ kubectl top pods -A --sort-by=cpu | head -20
STEP 4: Check HPA settings
$ kubectl get hpa -A
$ kubectl describe hpa <name>
STEP 5: Check for missing limits
$ kubectl get pods -A -o json | jq '.items[] | select(.spec.containers[].resources.limits == null) | .metadata.name'
STEP 6: Apply immediate fix
# Scale down runaway workload
# Apply resource limits
STEP 7: Check node count
$ kubectl get nodes
# Karpenter/Cluster Autoscaler may have added nodes
STEP 8: Escalate
34. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | Cost spike > 200% / autoscaling failure causing outage | 5 min | On-call + Platform + Management |
| SEV-2 | Cost spike 50-200% / PDB blocking scale-down | 15 min | On-call + Platform |
| SEV-3 | Cost anomaly / optimization opportunity | 1 hour | On-call |
| SEV-4 | Rightsizing recommendation | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
35. Junior-Level Questions
| Question | Expected Answer |
| What is HPA? | Scales replicas based on metrics |
| What is VPA? | Adjusts resource requests/limits |
| What is a resource request? | Minimum guaranteed resources |
| What is a resource limit? | Maximum allowed resources |
| What is a spot instance? | Discounted cloud capacity that can be reclaimed |
36. Mid-Level Questions
| Question | Expected Answer |
| What is KEDA? | Event-driven autoscaling |
| What is Karpenter? | Modern node provisioner |
| What is the HPA/VPA conflict? | Both scaling on CPU causes instability |
| What is bin-packing? | Packing pods densely on fewer nodes |
| What is a PDB? | Prevents too many pods from being unavailable |
37. Senior-Level Questions
| Question | Expected Answer |
| How do you coordinate HPA, VPA, and KEDA? | HPA on CPU, VPA on memory (Off mode), KEDA on events |
| How do you choose between Karpenter and CAS? | Karpenter for EKS/AKS; CAS for GKE |
| How do you optimize spot instance usage? | Diversify types, use PDBs, graceful shutdown |
| How do you measure cost efficiency? | Utilization, cost per request, waste percentage |
| How do you handle cost anomalies? | Alerts, budgets, automated remediation |
38. Staff/Principal Questions
| Question | Expected Answer |
| Design a cost governance architecture. | Kubecost + VPA + HPA + Karpenter + quotas + budgets |
| How do you implement FinOps at scale? | Showback, chargeback, budgets, automated optimization |
| How do you handle multi-tenant cost allocation? | Labels, namespaces, Kubecost allocation |
| How do you balance cost and availability? | Spot with fallback, bin-packing with anti-affinity |
| How do you get 50% cost reduction? | Rightsizing + spot + bin-packing + Karpenter consolidation |
Summary Cheat Sheet
| Concept | Key Takeaway |
| HPA | Scales replicas based on metrics |
| VPA | Adjusts resource requests/limits |
| KEDA | Event-driven autoscaling, scale to zero |
| Cluster Autoscaler | Node scaling (3-4 min) |
| Karpenter | Node provisioning (45-60s), consolidation |
| Spot instances | 60-90% discount, interruption risk |
| Bin-packing | MostAllocated scoring |
| Node consolidation | Karpenter, Descheduler |
| PDB | Can block scale-down |
| Kubecost | Cost monitoring (IBM) |
| OpenCost | Cost monitoring (CNCF) |
| Goldilocks | VPA recommendations dashboard |
| Resource requests | Scheduler uses these, not usage |
| QoS | Guaranteed > Burstable > BestEffort |
| HPA behavior | Scale up fast, scale down slow |
| VPA + HPA conflict | Never both on CPU |
| Karpenter consolidation | 50% node reduction in production |
| Cost governance | Visibility → Optimization → Scaling → Governance |
Stage 11: Cluster Lifecycle & Operations — The Comprehensive Guide
PART 1: CORE THEORY
1. The Cluster Lifecycle
A Kubernetes cluster is not a static artifact. It has a lifecycle: provision, operate, upgrade, scale, and eventually retire. Every phase must be planned, automated, and tested.
The Five Phases
| Phase | Activities | Tools |
| Provisioning | Create control plane, join nodes, install CNI/CSI | kubeadm, Cluster API, managed services |
| Operations | Monitor, scale, back up, rotate certs | Prometheus, Velero, cert-manager |
| Upgrades | Control plane, then workers, then validation | kubeadm, Cluster API |
| Disaster Recovery | Restore from etcd snapshot or Velero backup | etcdctl, Velero |
| Retirement | Drain nodes, delete cluster, clean up cloud resources | kubectl, Terraform |
Why Lifecycle Management Matters
A poorly prepared update represents a significant portion of cluster incidents. IT teams spend an average of 34 working days per year resolving Kubernetes issues, and a large share comes from unplanned upgrade problems.
2. Kubernetes Version Skew Policy
The version skew policy defines which combinations of component versions are supported. Violating it causes subtle failures that are hard to diagnose.
Supported Versions
The Kubernetes project maintains release branches for the most recent three minor releases (e.g., 1.37, 1.36, 1.35). Kubernetes 1.19 and newer receive approximately 1 year of patch support.
Version Skew Rules
| Component | Rule |
| kube-apiserver (HA) | Newest and oldest instances must be within one minor version |
| kubelet | Must not be newer than apiserver; may be up to three minor versions older |
| kube-proxy | Must not be newer than apiserver; may be up to three minor versions older |
| kubectl | Within one minor version of apiserver (older or newer) |
Example: HA Cluster with Version Skew
text
kube-apiserver instances: 1.37 and 1.36
kubelet supported: 1.36, 1.35, 1.34
Note: 1.37 is NOT supported because that would be newer than the 1.36 apiserver instance[reference:2]
The Golden Rule
Never more than one minor version difference between components during an upgrade. Upgrade control plane first, then workers one by one.
3. Cluster Upgrades
Kubernetes upgrades follow a strict control plane first, then workers one by one sequence.
The Three Phases
text
Phase 1: Control Plane Upgrade
│
├── Upgrade API server
├── Upgrade controller manager
├── Upgrade scheduler
└── Upgrade etcd
│
▼
Phase 2: Worker Node Upgrade (one at a time)
│
├── Cordon node
├── Drain node (evict pods)
├── Upgrade kubelet and kube-proxy
├── Uncordon node
└── Repeat for each node
│
▼
Phase 3: Validation
│
├── Check node status
├── Verify workloads
└── Monitor for issues
Pre-Upgrade Checklist
| Step | Command |
| Check current version | kubectl version --short |
| Check target version | kubeadm upgrade plan |
| Audit deprecated APIs | kubectl get --raw /metrics | grep apiserver_requested_deprecated_apis |
| Back up etcd | etcdctl snapshot save |
| Check PDBs | kubectl get pdb -A |
| Verify node health | kubectl get nodes |
kubeadm Upgrade Commands
bash
# On control plane node
sudo kubeadm upgrade plan
sudo kubeadm upgrade apply v1.36.0
# On other control plane nodes
sudo kubeadm upgrade node
# On worker nodes (one at a time)
kubectl cordon <node>
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data
sudo kubeadm upgrade node
kubectl uncordon <node>
Upgrade Timeline
| Cluster Size | Expected Time |
| 3 nodes | 30–60 minutes |
| 10 nodes | 2–4 hours |
| 50 nodes | 8–12 hours |
| 100+ nodes | 1–2 days |
4. Node Lifecycle Management
Node lifecycle operations are the foundation of cluster maintenance.
Cordon
Cordon marks a node as unschedulable. Existing Pods continue running, but new Pods won't be scheduled.
bash
kubectl cordon <node>
Drain
Drain evicts all Pods from a node (except DaemonSets) and marks it unschedulable.
bash
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data
Options:
| Flag | Purpose |
--ignore-daemonsets | Skip DaemonSet Pods (they can't be evicted) |
--delete-emptydir-data | Delete Pods using emptyDir |
--force | Force deletion of Pods not managed by controllers |
--grace-period | Override default grace period |
--timeout | Timeout for the drain |
Uncordon
Uncordon makes the node schedulable again.
bash
kubectl uncordon <node>
PodDisruptionBudgets and Drain
PDBs protect applications during voluntary disruptions. A PDB defines how many pods must remain available during a drain. Without PDBs, a node drain can take your entire service offline if all replicas are on one node.
Common PDB mistakes:
| Mistake | Impact |
| Never allow disruptionsAllowed to equal 0 in steady state | Drain stalls forever |
| Using PDBs for single-replica deployments | Drain blocks |
| Scope PDB selector too broadly | Unexpected protection |
| Not setting PDBs at all | Service outage during drain |
Graceful Node Shutdown
Kubernetes supports graceful node shutdown — when the OS signals shutdown, kubelet terminates Pods gracefully.
yaml
# /var/lib/kubelet/config.yaml
shutdownGracePeriod: 30s
shutdownGracePeriodCriticalPods: 10s
5. etcd Backup and Restore
etcd stores 100% of Kubernetes cluster state — namespaces, deployments, services, RBAC, CRDs, secrets. Without a functional etcd backup, corruption or data loss means complete cluster reconstruction.
Manual Snapshot
bash
export ETCDCTL_API=3
etcdctl snapshot save /backup/etcd-$(date +%Y%m%d-%H%M%S).db \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key
# Verify integrity
etcdctl snapshot status /backup/etcd-20260228-143000.db --write-out=table
Automated etcd Backup (CronJob)
yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: etcd-backup
namespace: kube-system
spec:
schedule: "0 */6 * * *" # Every 6 hours
jobTemplate:
spec:
template:
spec:
hostNetwork: true
containers:
- name: backup
image: registry.k8s.io/etcd:3.5.12-0
command:
- /bin/sh
- -c
- |
etcdctl snapshot save /backup/etcd-$(date +%Y%m%d-%H%M%S).db
find /backup -mtime +7 -delete
env:
- name: ETCDCTL_API
value: "3"
volumeMounts:
- name: etcd-certs
mountPath: /etc/kubernetes/pki/etcd
readOnly: true
- name: backup
mountPath: /backup
Restore Procedure
- Stop the API server (move static pod manifests)
- Remove old etcd data from
/var/lib/etcd - Restore the snapshot with
etcdutl snapshot restore - Restore static pod manifests
- Restart kubelet
- Verify cluster health
Critical: Test restores in staging before production. The etcd snapshot restore process modifies cluster identifiers.
PART 2: ADVANCED CONCEPTS
6. Velero
Velero (formerly Heptio Ark) is the de-facto standard for Kubernetes workload backup and restore. It backs up Kubernetes objects and persistent volume data, and restores them to the same or a different cluster.
What Velero Backs Up
| Component | Method |
| Kubernetes objects | API server export |
| Persistent volumes | CSI snapshots or file-system backup |
| CRDs | API server export |
| Namespaces | Selective backup |
| Secrets | Encrypted storage |
Velero Architecture
text
Velero CLI → Velero Server (in-cluster) → Object Storage (S3, GCS, Azure Blob)
│
├── Node Agent (DaemonSet) → PV data
└── CSI Snapshotter → Volume snapshots
Installing Velero
bash
velero install \
--provider aws \
--plugins velero/velero-plugin-for-aws:v1.14.0 \
--bucket my-velero-backups \
--backup-location-config region=us-east-1 \
--snapshot-location-config region=us-east-1 \
--secret-file ./credentials-velero
Backup and Restore
bash
# Create a backup
velero backup create production-backup --include-namespaces production
# Check status
velero backup describe production-backup
velero backup logs production-backup
# Restore
velero restore create --from-backup production-backup
# Schedule backups
velero schedule create daily-backup \
--schedule="0 2 * * *" \
--include-namespaces production \
--ttl 168h # 7-day retention
Velero Best Practices
| Practice | Why |
| Use schedules, not manual backups | Consistency |
| Set appropriate TTL | Cost control (7–30 days typical) |
| Verify backup content | Check datauploads, not just Completed status |
| Test restores regularly | Backups without restores are useless |
| Store offsite | Protect against site failure |
| Encrypt backups | Security |
The Critical Distinction: etcd vs Velero
The etcd snapshot is your control-plane insurance. Velero is your workload insurance and your only way to restore selectively or into a new cluster.
7. etcd Compaction and Defragmentation
Why etcd Grows
etcd's database file grows over time even when you're not adding objects. Compaction removes old revisions logically, but the bbolt backend does not shrink the file on disk. Without defragmentation, the file grows indefinitely.
The Two Operations
| Operation | What It Does |
| Compaction | Removes old revisions from the logical keyspace |
| Defragmentation | Reclaims disk space by removing gaps from deleted keys |
Automatic Compaction
The Kubernetes API server passes --etcd-compaction-interval to trigger compaction periodically.
Manual Defragmentation
bash
# Check fragmentation
etcdctl endpoint status --cluster --write-out=table
# Defragment one member at a time
etcdctl defrag --endpoints=https://etcd-1:2379
# Verify
etcdctl endpoint status --cluster --write-out=table
Warning: Defragmentation blocks the etcd member for the duration. Do one member at a time, never all at once.
etcd-defrag Tool
The community maintains etcd-defrag, a smarter defragmentation tool that:
- Checks health of all members before starting
- Defragments the leader last
- Supports rule-based defragmentation
- Auto-disarms NOSPACE alarms
Monitoring etcd Size
bash
# Database size
etcdctl endpoint status --write-out=table
# Alarm if DB size > 2 GB (default quota is 2 GB)
etcdctl alarm list
Production rule: Alert when etcd DB size exceeds 1.5 GB. Defragment proactively.
8. Certificate Rotation
Kubernetes uses TLS certificates for all control plane communication. These certificates expire, and if they do, the cluster breaks.
Certificate Types and Validity
| Certificate | Default Validity |
| kube-apiserver serving cert | 1 year |
| kube-apiserver client cert | 1 year |
| etcd serving cert | 1 year |
| etcd peer cert | 1 year |
| kubelet client cert | 1 year |
| kubelet serving cert | 1 year |
| CA certificate | 10 years |
Rotation Methods
| Method | Description |
| kubeadm | kubeadm certs renew all |
| Managed services | Automatic (EKS, AKS, GKE) |
| Rancher | rke certificate rotate |
| Manual | Regenerate and replace |
kubeadm Certificate Rotation
bash
# Check expiry
kubeadm certs check-expiration
# Rotate all
sudo kubeadm certs renew all
# Restart control plane components
sudo systemctl restart kubelet
Managed Service CA Rotation (2026)
Amazon EKS now supports certificate authority (CA) rotation with automated lifecycle management, enabling customers to rotate their cluster's CA through a managed lifecycle with automated safeguards.
Certificate Rotation Best Practices
| Practice | Why |
| Rotate before expiry | Avoid cluster outage |
| Plan a maintenance window | Control plane briefly unavailable |
| Back up certificates | Rollback safety |
| Test in staging | Verify procedure |
| Automate with managed services | Reduce operational burden |
9. Cluster API (CAPI)
Cluster API (CAPI) is a Kubernetes sub-project that lets you manage the lifecycle of Kubernetes clusters using Kubernetes itself. You define a cluster in YAML, apply it to a management cluster, and CAPI controllers provision the infrastructure, bootstrap the nodes, and install Kubernetes.
CAPI Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ CLUSTER API ARCHITECTURE │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Management Cluster (runs CAPI controllers) │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │ CAPI Core │ │ Infra │ │ Bootstrap │ │ │
│ │ │ Controllers │ │ Provider │ │ Provider │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Workload Clusters │ │
│ │ • Cluster 1 (AWS) │ │
│ │ • Cluster 2 (vSphere) │ │
│ │ • Cluster 3 (bare metal) │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
The Four Layers
| Layer | Purpose | Examples |
| Core | Cluster and Machine abstractions | Cluster, Machine, MachineSet |
| Infrastructure | Cloud resource provisioning | AWSCluster, VSphereCluster |
| Bootstrap | Turn machine into K8s node | KubeadmConfig, TalosConfig |
| Control Plane | Manage control plane | KubeadmControlPlane |
CAPI v1.12 (January 2026)
The v1.12 release introduced in-place updates and chained upgrades:
- In-place updates allow users to make changes on existing machines without delete-and-recreate
- Chained upgrades allow clusters using managed topologies to upgrade by more than one minor Kubernetes version through efficient sequential upgrades
CAPI Cluster Definition
yaml
apiVersion: cluster.x-k8s.io/v1beta1
kind: Cluster
metadata:
name: production
spec:
clusterNetwork:
pods:
cidrBlocks: ["192.168.0.0/16"]
controlPlaneRef:
apiVersion: controlplane.cluster.x-k8s.io/v1beta1
kind: KubeadmControlPlane
name: production-control-plane
infrastructureRef:
apiVersion: infrastructure.cluster.x-k8s.io/v1beta1
kind: AWSCluster
name: production
CAPI Strengths
| Strength | Why |
| Consistency | Same API across clouds |
| GitOps compatibility | YAML in version control |
| Automated upgrades | CAPI sequences control plane upgrades |
| Multi-cloud | 37+ infrastructure providers |
When to Use CAPI
| Scenario | CAPI? |
| Multi-cloud fleet | ✅ Yes |
| On-prem + cloud | ✅ Yes |
| Single managed cluster | ❌ Use managed service |
| Small team | ❌ Use managed service |
CAPI standardizes how clusters are created and managed, but it does little to improve how clusters behave in production or reduce operational friction for SREs. Use it when fleet consistency matters more than simplicity.
10. Multi-Cluster Management
Karmada
Karmada (Kubernetes Armada) is a CNCF-graduated project for multi-cluster, multi-cloud Kubernetes orchestration. It extends the standard Kubernetes API with centralized placement, propagation, failover, and multi-cluster autoscaling.
Karmada Architecture
| Component | Purpose |
| Karmada Control Plane | Central API, scheduler, controllers |
| Member Clusters | Workload clusters (push or pull mode) |
| ResourceBinding | Workload distribution decisions |
| PropagationPolicy | Where workloads should run |
Karmada v1.19 (2026)
The v1.19 release advances multi-component scheduling for distributed AI training jobs and promotes priority-based scheduling to Beta, enabled by default.
Karmada Use Cases
| Use Case | Description |
| Hybrid cloud | Run workloads across AWS, GCP, on-prem |
| Multi-region | Distribute workloads globally |
| AI/ML training | Schedule across GPU clusters |
| Disaster recovery | Active-active multi-cluster |
Fleet (Rancher)
Fleet is Rancher's multi-cluster management tool. It deploys applications across clusters with GitOps.
Comparison
| Tool | Approach | CNCF Status |
| Karmada | Central control plane, propagation policies | Graduated |
| Fleet | GitOps-driven, Rancher-native | Incubating |
| Cluster API | Declarative cluster provisioning | Production-ready |
| vCluster | Virtual clusters | CNCF sandbox |
11. Node Problem Detector
Node Problem Detector (NPD) is a DaemonSet that runs on every node. It monitors system logs, runs custom checks, and reports problems as node conditions or events that Kubernetes and operators can act upon.
What NPD Detects
| Problem Type | Example |
| Kernel deadlocks | Hung tasks, soft lockups |
| Hardware failures | Disk errors, memory errors |
| Network problems | NIC down, packet loss |
| Resource pressure | Disk, memory, PID pressure |
NPD Architecture
text
NPD DaemonSet (per node)
│
├── system-log-monitor (kernel logs)
├── custom-plugin-monitor (custom checks)
└── kernel-monitor (kernel events)
│
▼
API Server (NodeCondition + Events)
│
▼
Scheduler / Autoscaler / Operators
Deploying NPD
yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: node-problem-detector
namespace: kube-system
spec:
selector:
matchLabels:
app: node-problem-detector
template:
metadata:
labels:
app: node-problem-detector
spec:
hostNetwork: true
containers:
- name: node-problem-detector
image: registry.k8s.io/node-problem-detector/node-problem-detector:v0.8.19
securityContext:
privileged: true
volumeMounts:
- name: log
mountPath: /var/log
readOnly: true
12. Disaster Recovery Strategy
RTO and RPO
| Metric | Definition | Depends On |
| RTO (Recovery Time Objective) | Maximum acceptable downtime | Recovery speed |
| RPO (Recovery Point Objective) | Maximum acceptable data loss | Backup frequency |
The Four Recovery Layers
For a recovery to count, four layers must come back:
- Cluster infrastructure (nodes, networking)
- Cluster state (etcd / API objects)
- Persistent data (volumes)
- Traffic path (DNS, ingress, load balancers)
Recovery fails at the joins between the layers: a restored cluster with no data, restored data with no traffic path, an application definition that provisions an empty volume.
DR Strategy Matrix
| Strategy | RPO | RTO | Cost |
| Backup/Restore | Hours | Hours | $ |
| Snapshot | Minutes | Minutes | $$ |
| Replication | Seconds | Minutes | $$$ |
| Active-Active | Zero | Zero | $$$$ |
DR Testing
| Test | Frequency |
| Restore etcd snapshot | Monthly |
| Restore from Velero | Monthly |
| Full cluster rebuild | Quarterly |
| Multi-region failover | Quarterly |
13. Infrastructure as Code for Clusters
Terraform for Cluster Provisioning
hcl
resource "aws_eks_cluster" "production" {
name = "production"
role_arn = aws_iam_role.eks.arn
version = "1.36"
vpc_config {
subnet_ids = aws_subnet.private[*].id
}
}
resource "aws_eks_node_group" "workers" {
cluster_name = aws_eks_cluster.production.name
node_group_name = "workers"
node_role_arn = aws_iam_role.nodes.arn
subnet_ids = aws_subnet.private[*].id
instance_types = ["m5.xlarge"]
scaling_config {
desired_size = 3
max_size = 10
min_size = 1
}
}
Crossplane for Kubernetes-Native Infrastructure
Crossplane extends Kubernetes to manage cloud resources as CRDs. Instead of Terraform, you define cloud resources as Kubernetes objects.
yaml
apiVersion: rds.aws.upbound.io/v1beta1
kind: Instance
metadata:
name: production-db
spec:
forProvider:
region: us-east-1
instanceClass: db.t3.medium
engine: postgres
allocatedStorage: 100
PART 3: PRODUCTION FAILURE MODES
14. Top 10 Cluster Lifecycle Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | etcd quorum lost | API server unresponsive | Multiple etcd nodes down | Restore from snapshot |
| 2 | Upgrade blocked by PDB | Drain stalls | PDB too strict | Adjust PDB, add capacity |
| 3 | Certificate expired | kubelet can't connect | No rotation | Rotate certificates |
| 4 | Deprecated API removed | Workloads fail after upgrade | No pre-upgrade audit | Audit with kubectl convert |
| 5 | etcd disk full | API errors, NOSPACE alarm | DB grew beyond quota | Defragment, increase quota |
| 6 | Velero backup failure | No backup for DR | Misconfigured storage | Fix backup location |
| 7 | Node stuck draining | Drain never completes | Pods without controllers | Use --force |
| 8 | Version skew violation | Subtle failures | Components on incompatible versions | Follow skew policy |
| 9 | Cluster API reconciliation loop | Cluster stuck | Provider bug | Check CAPI logs |
| 10 | Multi-cluster split brain | Inconsistent state | Network partition | Karmada failover |
15. Cluster Lifecycle Debugging Runbook
"Upgrade Failed" — Step-by-Step
text
STEP 1: Check upgrade status
$ kubeadm upgrade plan
$ kubectl get nodes
STEP 2: Check control plane pods
$ kubectl get pods -n kube-system
STEP 3: Check etcd health
$ etcdctl endpoint health --cluster
$ etcdctl endpoint status --cluster --write-out=table
STEP 4: Check certificates
$ kubeadm certs check-expiration
STEP 5: Check events
$ kubectl get events -A --sort-by=.metadata.creationTimestamp
STEP 6: If upgrade is stuck
# Check kubelet logs
$ journalctl -u kubelet -n 100
# Check kube-apiserver logs
$ crictl logs $(crictl ps | grep kube-apiserver | awk '{print $1}')
STEP 7: Rollback if needed
# Restore etcd snapshot
# Downgrade is not supported
STEP 8: Escalate
16. Blast Radius Analysis
What Happens When Cluster Lifecycle Fails?
| Component | Impact | Severity |
| etcd quorum lost | Cluster unmanageable | SEV-1 |
| All control planes down | Cluster unmanageable | SEV-1 |
| Certificate expired | Cluster breaks | SEV-1 |
| Failed upgrade | Partial control plane | SEV-1 |
| Velero backup failed | No DR protection | SEV-2 |
| PDB blocks drain | Upgrade stalls | SEV-2 |
| Node drain stuck | Maintenance blocked | SEV-3 |
PART 4: CAPACITY PLANNING & COST MODELING
17. Upgrade Cost and Time Modeling
Upgrade Time by Cluster Size
| Nodes | Control Plane | Workers | Total |
| 3 | 15 min | 15 min | 30 min |
| 10 | 20 min | 2 hours | 2.5 hours |
| 50 | 30 min | 8 hours | 8.5 hours |
| 100+ | 45 min | 16 hours | 17 hours |
Upgrade Cost
| Cost Component | Estimate |
| Engineering time | 2–8 hours |
| Maintenance window | 2–12 hours |
| Rollback cost | 1–4 hours |
18. Backup Storage Cost Modeling
etcd Snapshot Storage
| Cluster Size | Snapshot Size | Frequency | Monthly Storage |
| Small | 50 MB | Daily | 1.5 GB |
| Medium | 500 MB | Daily | 15 GB |
| Large | 2 GB | Daily | 60 GB |
Velero Backup Storage
| Data Size | Backup Size | Retention | Monthly Storage |
| 10 GB | 5 GB (compressed) | 7 days | 35 GB |
| 100 GB | 50 GB | 7 days | 350 GB |
| 1 TB | 500 GB | 7 days | 3.5 TB |
Cost Optimization
| Strategy | Savings |
| Compression | 50% |
| Deduplication | 30–50% |
| Lifecycle policies | 40–60% |
| Object storage (S3 Glacier) | 80% |
19. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Cluster Operations SLA Design
| Target | Architecture |
| 99.9% | Single control plane, etcd snapshots |
| 99.99% | HA control plane, automated backups, tested DR |
| 99.999% | Multi-cluster, active-active, chaos-tested |
PART 5: ARCHITECTURE & STRATEGY
20. Fleet Management Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ FLEET MANAGEMENT │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Management Cluster │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │ Cluster API │ │ Argo CD │ │ Prometheus │ │ │
│ │ │ Controllers │ │ (GitOps) │ │ (Federation)│ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ┌───────────────┼───────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Cluster │ │ Cluster │ │ Cluster │ │
│ │ us-east-1 │ │ eu-west-1 │ │ ap-south-1 │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
21. Multi-Cluster Governance
Policy Enforcement Across Clusters
| Tool | Approach |
| Kyverno | ClusterPolicy, multi-cluster via Cluster API |
| OPA Gatekeeper | ConstraintTemplates |
| Karmada | PropagationPolicy |
| Fleet | GitOps bundles |
Cluster Baseline
| Baseline | Description |
| Security | RBAC, PSS, NetworkPolicy, audit logging |
| Observability | Prometheus, logging, tracing |
| Backup | Velero, etcd snapshots |
| Upgrade | Version skew policy, upgrade window |
22. Compliance & Security for Cluster Operations
| Framework | Cluster Ops Requirement |
| PCI-DSS | Change management, audit logs, encryption |
| HIPAA | Audit trails, access controls |
| SOC2 | Change management, monitoring |
| FedRAMP | FIPS 140-2, configuration baselines |
PART 6: HANDS-ON LABS
Lab 1: Plan and Apply a Kubernetes Upgrade
bash
# Check current version
kubectl version --short
# Check upgrade path
sudo kubeadm upgrade plan
# Apply control plane upgrade
sudo kubeadm upgrade apply v1.36.0
# Verify
kubectl get nodes
kubectl get pods -n kube-system
Lab 2: Cordon, Drain, and Uncordon a Node
bash
# Cordon
kubectl cordon <node>
# Drain (with timeout)
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data --timeout=300s
# Verify pods moved
kubectl get pods -o wide
# Uncordon
kubectl uncordon <node>
Lab 3: etcd Snapshot Backup and Restore
bash
# Backup
ETCDCTL_API=3 etcdctl snapshot save /tmp/etcd-backup.db \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key
# Verify
ETCDCTL_API=3 etcdctl snapshot status /tmp/etcd-backup.db --write-out=table
# Restore (in test environment)
# 1. Stop API server
# 2. Restore snapshot
# 3. Restart API server
Lab 4: Velero Backup and Restore
bash
# Install Velero
velero install --provider aws --bucket velero-backup ...
# Create backup
velero backup create test-backup --include-namespaces default
# Delete namespace
kubectl delete namespace default --force
# Restore
velero restore create --from-backup test-backup
# Verify
kubectl get all
Lab 5: Certificate Rotation
bash
# Check expiry
kubeadm certs check-expiration
# Rotate
sudo kubeadm certs renew all
# Restart kubelet
sudo systemctl restart kubelet
# Verify
kubeadm certs check-expiration
Lab 6: etcd Defragmentation
bash
# Check fragmentation
etcdctl endpoint status --cluster --write-out=table
# Defragment
etcdctl defrag --endpoints=https://etcd-1:2379
# Verify
etcdctl endpoint status --cluster --write-out=table
Lab 7: Cluster API Cluster Provisioning
bash
# Install clusterctl
curl -L https://github.com/kubernetes-sigs/cluster-api/releases/download/v1.12.0/clusterctl-linux-amd64 -o clusterctl
chmod +x clusterctl
# Initialize management cluster
clusterctl init --infrastructure aws
# Generate cluster config
clusterctl generate cluster production --kubernetes-version v1.36.0 > production.yaml
# Apply
kubectl apply -f production.yaml
# Check status
clusterctl describe cluster production
Lab 8: Full Disaster Recovery Drill
bash
# 1. Take etcd snapshot
etcdctl snapshot save /backup/pre-drill.db ...
# 2. Take Velero backup
velero backup create dr-drill --include-namespaces production
# 3. Simulate disaster (delete namespace)
kubectl delete namespace production --force
# 4. Restore from Velero
velero restore create --from-backup dr-drill
# 5. Verify
kubectl get all -n production
# 6. Document RTO
Lab 9: Multi-Cluster Management with Karmada
bash
# Install Karmada
helm repo add karmada https://raw.githubusercontent.com/karmada-io/karmada/master/charts
helm install karmada karmada/karmada -n karmada-system --create-namespace
# Join member clusters
karmadactl join member1 --cluster-kubeconfig=/path/to/member1
# Create PropagationPolicy
cat <<'EOF' | kubectl apply -f -
apiVersion: policy.karmada.io/v1alpha1
kind: PropagationPolicy
metadata:
name: nginx-propagation
spec:
resourceSelectors:
- apiVersion: apps/v1
kind: Deployment
name: nginx
placement:
clusterAffinity:
clusterNames:
- member1
- member2
EOF
# Deploy workload
kubectl create deployment nginx --image=nginx --replicas=6
PART 7: INCIDENT MANAGEMENT
32. Cluster Lifecycle Incident Post-Mortem Template
text
INCIDENT: etcd Quorum Lost During Upgrade
DATE: 2024-01-15
DURATION: 2 hours
SEVERITY: SEV-1
IMPACT: Cluster unmanageable. API server returned errors.
TIMELINE:
14:00 - Started control plane upgrade
14:15 - etcd member 1 failed to restart
14:20 - etcd member 2 failed to restart
14:25 - Quorum lost (1 of 3 members remaining)
14:30 - Initiated restore from snapshot
15:00 - Restored etcd from snapshot
15:30 - Cluster operational
16:00 - Upgrade completed
16:00 - Incident closed
ROOT CAUSE:
Disk I/O latency exceeded thresholds during upgrade.
Two etcd members failed health checks and were killed.
LESSONS LEARNED:
1. etcd needs dedicated SSD with low fsync latency.
2. Upgrade should be done during low-traffic windows.
3. etcd snapshots must be tested regularly.
ACTION ITEMS:
[ ] Move etcd to NVMe SSD (Owner: Platform)
[ ] Test etcd restore monthly (Owner: SRE)
[ ] Add etcd I/O monitoring (Owner: SRE)
33. On-Call Runbook: Upgrade Failure / etcd Outage
text
STEP 1: Check cluster health
$ kubectl get nodes
$ kubectl get pods -n kube-system
STEP 2: Check etcd
$ etcdctl endpoint health --cluster
$ etcdctl endpoint status --cluster --write-out=table
STEP 3: Check control plane pods
$ crictl ps | grep -E "apiserver|etcd|scheduler|controller"
STEP 4: Check logs
$ journalctl -u kubelet -n 100
$ crictl logs <container-id>
STEP 5: If etcd is down
$ systemctl restart etcd
# Or restore from snapshot
STEP 6: If upgrade is stuck
# Check kubeadm logs
# Check static pod manifests
STEP 7: Escalate
34. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | etcd quorum lost / all control planes down | 5 min | On-call + Platform + Management |
| SEV-2 | Upgrade failure / certificate expired | 15 min | On-call + Platform |
| SEV-3 | PDB blocks drain / backup failed | 1 hour | On-call |
| SEV-4 | Capacity planning warning | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
35. Junior-Level Questions
| Question | Expected Answer |
| What is the upgrade sequence? | Control plane first, then workers one by one |
| What is cordon? | Marks node unschedulable |
| What is drain? | Evicts pods from a node |
| What is an etcd snapshot? | Point-in-time copy of cluster state |
| What is Velero? | Backup and restore tool for Kubernetes |
36. Mid-Level Questions
| Question | Expected Answer |
| What is version skew? | Supported version differences between components |
| How do you back up etcd? | etcdctl snapshot save with certificates |
| What is a PDB? | Limits pods unavailable during voluntary disruptions |
| What is Karmada? | Multi-cluster orchestration platform |
| How do you rotate certificates? | kubeadm certs renew all |
37. Senior-Level Questions
| Question | Expected Answer |
| How do you test DR? | Regular restore drills, validate RTO/RPO |
| How do you handle etcd corruption? | Restore from snapshot, verify integrity |
| What is Cluster API? | Declarative cluster provisioning with Kubernetes |
| How do you scale upgrades across 100 clusters? | Cluster API, GitOps, automated pipelines |
| What is the etcd compaction vs defrag? | Compaction = logical removal, defrag = disk reclaim |
38. Staff/Principal Questions
| Question | Expected Answer |
| Design a fleet management architecture. | Management cluster + CAPI + GitOps + observability |
| How do you migrate 100 clusters to a new version? | Phased rollout, CAPI chained upgrades, canary clusters |
| How do you enforce consistency across clusters? | Policies, baselines, admission controllers |
| How do you handle multi-cloud DR? | Cross-region replication, tested failover |
| How do you get 99.999% for cluster management? | Multi-cluster active-active, chaos-tested |
Summary Cheat Sheet
| Concept | Key Takeaway |
| Version Skew | 3 minor versions for kubelet; 1 for apiserver HA |
| Upgrade Sequence | Control plane first, then workers one by one |
| kubeadm upgrade | plan → apply → node (workers) |
| Cordon | Mark node unschedulable |
| Drain | Evict pods, mark unschedulable |
| Uncordon | Make node schedulable |
| PDB | Protect during voluntary disruptions |
| etcd Backup | etcdctl snapshot save with certs |
| etcd Restore | etcdutl snapshot restore |
| etcd Compaction | Remove old revisions |
| etcd Defrag | Reclaim disk space |
| Velero | Workload backup and restore |
| Certificate Rotation | kubeadm certs renew all |
| Cluster API | Declarative cluster provisioning |
| CAPI v1.12 | In-place updates, chained upgrades |
| Karmada | Multi-cluster orchestration (CNCF Graduated) |
| Node Problem Detector | DaemonSet for node health |
| RTO/RPO | Recovery Time / Point Objectives |
| Fleet Management | Management cluster + CAPI + GitOps |
Stage 12: GPU Orchestration & Multi-Tenancy — The Comprehensive Guide
PART 1: CORE THEORY
1. The GPU Orchestration Problem
GPUs are the most expensive and most wasted resource in modern Kubernetes clusters. A single H100 node can run well over $30/hour in the cloud. The average GPU utilization in enterprise Kubernetes clusters sits at 5%, according to a Cast AI 2026 report measuring 23,000 clusters.
Why GPUs Are Different
| Aspect | CPU | GPU |
| Granularity | Millicores | Whole devices (unless shared) |
| Sharing | Native (time-slicing by kernel) | Requires explicit configuration |
| Cost | $0.05–$0.50/core/hour | $2–$30+/GPU/hour |
| Isolation | Process-level | Device-level (unless MIG) |
| Memory | Not a resource | Critical resource (VRAM) |
The Default Model
The NVIDIA device plugin advertises GPUs as integer resources (nvidia.com/gpu). When a pod requests nvidia.com/gpu: 1, Kubernetes schedules it onto a node with an available GPU and treats that device as allocated. One pod = one GPU.
This creates a GPU waste tax for inference workloads: ten services that each use 15% of a GPU still need ten physical GPUs with full-GPU allocation. The real demand is closer to 1.5 GPUs, but Kubernetes still reserves ten devices unless sharing is configured.
The Three Layers of GPU Management
| Layer | Purpose | Tools |
| Device Exposure | Make GPUs available to Kubernetes | NVIDIA Device Plugin, DRA |
| Scheduling | Place pods on GPU nodes | Default scheduler, KAI, Kueue |
| Sharing/Isolation | Multiple workloads per GPU | Time-slicing, MPS, MIG, DRA |
2. NVIDIA Device Plugin
The NVIDIA Device Plugin is the foundation of GPU orchestration. It registers GPUs as compute resources in the Kubernetes cluster and manages their allocation.
How the Device Plugin Works
text
┌─────────────────────────────────────────────────────────────┐
│ NVIDIA DEVICE PLUGIN FLOW │
│ │
│ 1. Plugin starts on GPU node (DaemonSet) │
│ 2. Detects GPUs via NVML │
│ 3. Registers with kubelet via Device Plugin API │
│ 4. Kubelet advertises "nvidia.com/gpu" as extended resource│
│ 5. Scheduler sees GPU as allocatable resource │
│ 6. Pod requests nvidia.com/gpu: N │
│ 7. Device plugin allocates N GPUs to the pod │
│ 8. Container runtime exposes devices to container │
└─────────────────────────────────────────────────────────────┘
Installation (GPU Operator)
The recommended way to install the device plugin is via the NVIDIA GPU Operator:
bash
# Add NVIDIA Helm repository
helm repo add nvidia https://helm.ngc.nvidia.com/nvidia
helm repo update
# Install GPU Operator
helm install gpu-operator nvidia/gpu-operator \
--namespace gpu-operator \
--create-namespace \
--set driver.enabled=true \
--wait
# Verify
kubectl get pods -n gpu-operator
kubectl get nodes -l nvidia.com/gpu.present=true
Verifying GPU Detection
bash
# Check GPU resources on nodes
kubectl describe node <gpu-node-name> | grep nvidia.com/gpu
# Should show something like: nvidia.com/gpu: 4
What the GPU Operator Manages
| Component | Purpose |
| Driver | NVIDIA kernel modules |
| Container Toolkit | Exposes GPUs to containers |
| Device Plugin | Registers GPUs with kubelet |
| DCGM Exporter | GPU metrics |
| MIG Manager | MIG partition management |
| Node Feature Discovery | Labels nodes with GPU model |
2026: CDI Injection Mode
NVIDIA's OpenShell project switched device plugin to CDI (Container Device Interface) injection mode in March 2026. CDI is the modern standard for exposing devices to containers, replacing the older device mount approach.
Latest Version (2026)
NVIDIA k8s-device-plugin v0.20.0 (August 2026) adds:
- Configurable packed/distributed allocation policy for replicated and MIG resources
- Prefer distinct GPU allocation for better fault isolation
3. GPU Scheduling in Kubernetes
The Default Scheduling Model
GPUs are advertised as extended resources (nvidia.com/gpu). The scheduler treats them as integer counts.
yaml
apiVersion: v1
kind: Pod
metadata:
name: gpu-pod
spec:
containers:
- name: cuda-app
image: nvidia/cuda:12.0-base
resources:
limits:
nvidia.com/gpu: 1 # Request 1 GPU
Key constraint: GPUs are only available in limits, not requests. Requesting a GPU implicitly sets the request equal to the limit.
GPU Node Pools
Production clusters use dedicated GPU node pools with:
| Configuration | Purpose |
| Taint | Keep non-GPU workloads off GPU nodes |
| Label | Identify GPU type/model |
| Node selector/affinity | Target specific GPU types |
yaml
# Taint GPU nodes
kubectl taint nodes gpu-node-1 nvidia.com/gpu=present:NoSchedule
# Label GPU nodes
kubectl label nodes gpu-node-1 nvidia.com/gpu.product=NVIDIA-A100-SXM4-40GB
kubectl label nodes gpu-node-1 nvidia.com/gpu.memory=40960
Pod Scheduling for GPUs
yaml
apiVersion: v1
kind: Pod
metadata:
name: gpu-workload
spec:
tolerations:
- key: nvidia.com/gpu
operator: Exists
effect: NoSchedule
nodeSelector:
nvidia.com/gpu.product: NVIDIA-A100-SXM4-40GB
containers:
- name: training
image: pytorch/pytorch:2.0-cuda11.7
resources:
limits:
nvidia.com/gpu: 4 # Request 4 GPUs
GPU Scheduling Limitations
| Limitation | Impact |
| Integer-only | No fractional GPUs |
| No topology awareness | Scheduler doesn't know NVLink |
| No attribute-based scheduling | Can't request GPU with >40GB VRAM |
| No sharing | Unless explicitly configured |
These limitations are addressed by DRA (Dynamic Resource Allocation).
4. GPU Sharing Strategies
The three main NVIDIA-supported options are time-slicing, Multi-Process Service (MPS), and Multi-Instance GPU (MIG). Each solves the sharing problem differently.
Comparison
| Aspect | Time-Slicing | MPS | MIG |
| Mechanism | Software (CUDA context switching) | Software (CUDA concurrency) | Hardware (GPU partitioning) |
| Isolation | ❌ None | ⚠️ Limited | ✅ Full (dedicated SM + memory) |
| GPU Support | Most NVIDIA GPUs | Most NVIDIA GPUs | A100, A30, H100, H200+ |
| Memory Isolation | ❌ No | ❌ No | ✅ Yes |
| Fault Isolation | ❌ No | ❌ No | ✅ Yes |
| Configuration | Simple | Medium | Complex |
| Best For | Dev, non-critical | Trusted CUDA | Production, multi-tenant |
Time-Slicing
Time-slicing lets GPU processes take turns on a single physical device via CUDA context switching. It's the simplest way to share a GPU.
Configuration:
yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: time-slicing-config
namespace: gpu-operator
data:
any: |
version: v1
flags:
migStrategy: none
sharing:
timeSlicing:
resources:
- name: nvidia.com/gpu
replicas: 4
bash
# Update GPU Operator
helm upgrade gpu-operator nvidia/gpu-operator \
--namespace gpu-operator \
--set devicePlugin.config.name=time-slicing-config \
--set devicePlugin.config.default=any \
--reuse-values
# Verify (4 physical GPUs → 16 advertised)
kubectl describe node <gpu-node> | grep nvidia.com/gpu
# Should show: nvidia.com/gpu: 16
Key limitation: Time-slicing does not isolate memory or faults. One workload's memory pressure or CUDA fault can affect another tenant.
MPS (Multi-Process Service)
MPS improves concurrency for trusted CUDA workloads by allowing multiple processes to share the GPU's compute resources more efficiently than time-slicing.
When to use MPS: Multiple trusted workloads that need concurrent GPU access (e.g., multiple inference services from the same team).
Key limitation: A single client fault can affect other clients sharing the GPU.
MIG (Multi-Instance GPU)
MIG creates hardware-isolated GPU partitions. Each partition has its own SM (Stream Multiprocessor) and GPU memory.
MIG-capable GPUs: A100, A30, H100, H200, and newer MIG-capable data center GPUs.
| GPU | Max MIG Instances |
| A100 (40GB) | 7 |
| A100 (80GB) | 7 |
| H100 (80GB) | 7 |
| H200 | 7 |
When to use MIG: Production multi-tenant environments where performance guarantees and fault isolation are required.
PART 2: ADVANCED CONCEPTS
5. Multi-Instance GPU (MIG) Deep Dive
MIG partitions a single GPU into up to seven independent instances, each with its own:
- Stream Multiprocessors (SMs) — compute units
- GPU memory — dedicated VRAM
- Memory bandwidth — isolated
- L2 cache slices
MIG Profiles
| Profile | SMs | Memory | Use Case |
| 1g.5gb | 1/7 | 5 GB | Small inference |
| 2g.10gb | 2/7 | 10 GB | Medium inference |
| 3g.20gb | 3/7 | 20 GB | Large inference |
| 4g.20gb | 4/7 | 20 GB | Training |
| 7g.40gb | 7/7 | 40 GB | Full GPU |
Configuring MIG
MIG configuration is handled by the NVIDIA GPU Operator and MIG Manager.
yaml
# MIG configuration ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
name: mig-config
namespace: gpu-operator
data:
config.yaml: |
version: v1
mig-configs:
all-1g.5gb:
- devices: all
mig-enabled: true
mig-devices:
"1g.5gb": 7
all-2g.10gb:
- devices: all
mig-enabled: true
mig-devices:
"2g.10gb": 3
bash
# Apply MIG configuration
kubectl apply -f mig-config.yaml
# Update GPU Operator
helm upgrade gpu-operator nvidia/gpu-operator \
--namespace gpu-operator \
--set migManager.config.name=mig-config \
--reuse-values
Using MIG in Pods
yaml
apiVersion: v1
kind: Pod
metadata:
name: mig-pod
spec:
containers:
- name: app
image: nvidia/cuda:12.0-base
resources:
limits:
nvidia.com/mig-1g.5gb: 1 # Request specific MIG profile
MIG Benefits
| Benefit | Impact |
| Hardware isolation | No noisy neighbors |
| Fault isolation | One instance crash doesn't affect others |
| Memory guarantees | Dedicated VRAM per instance |
| Predictable performance | QoS guaranteed |
MIG Limitations
| Limitation | Impact |
| GPU support | Only A100, A30, H100, H200+ |
| Static profiles | Must be pre-configured |
| No dynamic reconfiguration | Requires GPU reset |
| Complexity | More operational overhead |
6. GPU Topology
For multi-GPU workloads (distributed training, large model inference), GPU topology matters. The way GPUs are connected affects communication bandwidth.
NVLink
NVLink is NVIDIA's high-speed interconnect between GPUs. It provides much higher bandwidth than PCIe.
| Connection | Bandwidth |
| PCIe Gen5 x16 | 128 GB/s |
| NVLink 3.0 (A100) | 600 GB/s |
| NVLink 4.0 (H100) | 900 GB/s |
NVSwitch
NVSwitch enables all-to-all NVLink connectivity between GPUs in a node (e.g., DGX H100 with 8 GPUs).
Topology-Aware Scheduling
The default Kubernetes scheduler is not topology-aware. Custom schedulers like KubeNexus and HAMi add topology awareness:
yaml
# HAMi topology-aware scheduling
metadata:
annotations:
hami.io/gpu-scheduler-policy: topology-aware
| Scheduler | Topology Support |
| Default K8s | ❌ None |
| KubeNexus | ✅ NVLink/NVSwitch, NUMA |
| HAMi | ✅ NVLink topology filter |
| KAI Scheduler | ✅ Gang scheduling + topology |
The Topology-Aware Filter
Topology-aware schedulers keep only cards whose NVLink/NVSwitch topology satisfies the Pod's multi-GPU request. For example, a request for 8 GPUs will only schedule on a node where all 8 GPUs are in the same NVSwitch domain.
7. Dynamic Resource Allocation (DRA) for GPUs
DRA (Dynamic Resource Allocation) is the future of GPU scheduling in Kubernetes. It replaces the integer-based extended resource model with a structured, attribute-aware API.
Why DRA
| Device Plugin | DRA |
| Integer counts only | Attribute-based requests |
| No topology awareness | Topology-aware |
| No sharing semantics | Native sharing support |
| Vendor-specific | Standard API |
DRA Concepts
| Concept | Purpose |
| DeviceClass | Describes device capabilities |
| ResourceSlice | Represents allocatable capacity |
| ResourceClaim | Declarative workload request |
| ResourceClaimTemplate | Template for claims |
NVIDIA DRA Driver
NVIDIA donated its DRA Driver for GPUs to the CNCF in 2026, transferring governance from a single vendor to full community ownership. The driver enables:
- Attribute-based scheduling aligned with device capabilities
- Integration with MIG and time-slicing mechanisms
- Better coordination between the scheduler and allocation lifecycle
DRA Example
yaml
apiVersion: resource.k8s.io/v1
kind: ResourceClaim
metadata:
name: gpu-claim
spec:
devices:
requests:
- name: gpu
deviceClassName: nvidia-gpu
selectors:
- cel:
expression: "device.attributes['memory'].value >= 40000"
DRA in Kubernetes 1.36
Kubernetes 1.36 brought several DRA features to beta/stable:
| Feature | Status | Purpose |
| Prioritized list | Stable | Fallback preferences (H100 → A100) |
| Extended resource support | Beta | Gradual migration from device plugin |
| Partitionable devices | Beta | MIG-like partitioning via DRA |
| Device taints | Beta | Taint faulty/reserved devices |
| Device binding conditions | Beta | Delay scheduling until device ready |
8. GPU Monitoring with DCGM
DCGM (Data Center GPU Manager) is NVIDIA's GPU telemetry system. The DCGM Exporter exposes GPU metrics for Prometheus.
Key GPU Metrics
| Metric | Meaning |
DCGM_FI_DEV_GPU_UTIL | GPU utilization % |
DCGM_FI_DEV_MEM_COPY_UTIL | Memory bandwidth utilization |
DCGM_FI_DEV_FB_USED | Framebuffer memory used (VRAM) |
DCGM_FI_DEV_GPU_TEMP | GPU temperature |
DCGM_FI_DEV_POWER_USAGE | Power consumption (watts) |
DCGM_FI_DEV_XID_ERRORS | GPU errors |
Deploying DCGM Exporter
DCGM Exporter is deployed as part of the GPU Operator:
bash
# Verify DCGM Exporter
kubectl get pods -n gpu-operator -l app=nvidia-dcgm-exporter
# Port-forward to test
kubectl port-forward -n gpu-operator svc/nvidia-dcgm-exporter 9400:9400
curl localhost:9400/metrics | grep DCGM_FI_DEV_GPU_UTIL
GPU Alerts
| Alert | Condition | Action |
| GPU Idle | DCGM_FI_DEV_GPU_UTIL < 5% for 30 min | Kill idle workload |
| GPU Memory Pressure | DCGM_FI_DEV_FB_USED > 90% | Increase GPU memory or MIG slice |
| GPU Temperature | DCGM_FI_DEV_GPU_TEMP > 85°C | Check cooling, throttle |
| GPU Errors | DCGM_FI_DEV_XID_ERRORS > 0 | Investigate hardware |
GPU Utilization Dashboard
Grafana dashboards for GPU monitoring show:
- GPU utilization per node/pod
- VRAM usage
- Temperature and power
- XID errors
- MIG instance utilization
9. GPU Multi-Tenancy Strategies
The Four Layers of GPU Isolation
| Layer | Mechanism | Isolation Level |
| Kubernetes | Namespaces, RBAC, ResourceQuota | Logical |
| Scheduling | PriorityClasses, node affinity | Placement |
| Hardware | MIG, time-slicing | Physical/Logical |
| Runtime | Kata Containers (microVM) | Hardware VM |
Layer 1: Kubernetes Namespaces and Quotas
yaml
apiVersion: v1
kind: ResourceQuota
metadata:
name: gpu-quota
namespace: team-a
spec:
hard:
requests.nvidia.com/gpu: "4"
limits.nvidia.com/gpu: "4"
Layer 2: MIG for Hardware Isolation
For production multi-tenant GPU clusters, MIG is essential:
| Tenant | MIG Profile | Guaranteed Resources |
| Team A | 2g.10gb | 2/7 SMs, 10 GB VRAM |
| Team B | 2g.10gb | 2/7 SMs, 10 GB VRAM |
| Team C | 3g.20gb | 3/7 SMs, 20 GB VRAM |
Layer 3: Kata Containers for Strongest Isolation
Kata Containers run each pod inside a lightweight virtual machine. GPUs are exposed via VFIO passthrough, and isolation is enforced at the hardware virtualization boundary.
NVIDIA collaborated with the CNCF Confidential Containers community to introduce GPU support for Kata Containers in 2026.
Layer 4: KAI Scheduler for Fair Sharing
KAI Scheduler (CNCF Sandbox) provides:
- Gang scheduling for coordinated multi-pod execution
- Hierarchical queues with Dominant Resource Fairness (DRF)
- Fair sharing of GPUs across teams
Multi-Tenancy Decision Matrix
| Tenant Type | Isolation Strategy |
| Internal teams | Namespaces + quotas + MIG |
| External customers | vCluster + MIG + Kata |
| Regulated workloads | Kata + MIG + dedicated nodes |
| Hostile tenants | Separate clusters |
10. KAI Scheduler
KAI Scheduler was accepted as a CNCF Sandbox project in 2026, marking its transition from an NVIDIA-governed tool to a community-developed standard.
KAI Scheduler Capabilities
| Capability | Purpose |
| Gang scheduling | All-or-nothing placement for distributed jobs |
| Hierarchical queues | Team quotas with DRF |
| Sub-GPU allocation | Fractional GPU support |
| Pre-scheduling simulation | Reduce preemption overhead |
| Fair sharing | Prevent team starvation |
When to Use KAI Scheduler
| Use Case | KAI Scheduler? |
| Distributed training | ✅ Yes |
| Multi-team GPU sharing | ✅ Yes |
| Simple inference | ❌ Default scheduler |
| Single-team cluster | ❌ Default scheduler |
11. Kueue and Volcano
Kueue
Kueue is a Kubernetes-native job queueing system. It admits jobs based on quotas and priorities.
yaml
apiVersion: kueue.x-k8s.io/v1beta1
kind: ClusterQueue
metadata:
name: gpu-queue
spec:
namespaceSelector: {}
resourceGroups:
- coveredResources: ["nvidia.com/gpu"]
flavors:
- name: default
resources:
- name: nvidia.com/gpu
nominalQuota: 8
Volcano
Volcano is a CNCF incubating project for batch and AI/ML scheduling. It supports:
- Gang scheduling
- Fair-share scheduling
- Queue-based scheduling
- Topology-aware scheduling
Kueue vs Volcano
| Aspect | Kueue | Volcano |
| Focus | Job queueing | Full batch scheduler |
| Gang scheduling | ✅ | ✅ |
| Fair sharing | ✅ | ✅ |
| Topology awareness | Limited | ✅ |
| CNCF Status | Incubating | Incubating |
12. GPU Cost Optimization
The Five Strategies
| Strategy | Savings | Best For |
| Spot instances | 70–91% | Fault-tolerant training |
| Right-sizing GPU | 30–50% | All workloads |
| MIG/time-slicing | 50–70% | Inference |
| Autoscaling | Variable | Inference |
| Reserved instances | 30–60% | Predictable baseline |
Training vs Inference Cost Profiles
| Aspect | Training | Inference |
| Pattern | Batch, predictable | Continuous, variable |
| Duration | Hours to days | 24/7 |
| Optimization | Spot + checkpointing | Autoscaling + sharing |
| Commitment | Reserved instances | Baseline commitments |
Spot Instances for Training
Spot instances work well for fault-tolerant training (checkpointing every N minutes), delivering 70–91% cost reductions compared to on-demand pricing.
yaml
# Spot node pool toleration
spec:
tolerations:
- key: "spot-instance"
operator: "Equal"
value: "true"
effect: "NoSchedule"
GPU Memory Right-Sizing
| Model Size | Recommended GPU | VRAM |
| 7B params | A100 40GB | 16 GB (FP16) |
| 13B params | A100 40GB | 26 GB (FP16) |
| 70B params | A100 80GB / H100 | 140 GB (FP16) |
| Fine-tuning 7B | A100 40GB | 20 GB |
Cost Per Token Optimization
For inference, the optimization goal is cost per token:
| Strategy | Impact |
| Mix GPU generations | H100 for prefill, A100 for decode |
| MIG for small models | Share GPU across models |
| Autoscale on traffic | Scale to zero when idle |
| KV-cache optimization | Reduce VRAM per request |
13. Kata Containers for GPU Isolation
Kata Containers run each pod inside a lightweight virtual machine, providing hardware-level isolation.
How Kata Works with GPUs
text
┌─────────────────────────────────────────────────────────────┐
│ KATA CONTAINERS + GPU │
│ │
│ Pod → Kata VM (microVM) → VFIO Passthrough → GPU │
│ │
│ • Each pod gets its own microVM │
│ • GPU is passed through via VFIO │
│ • Isolation at hardware virtualization boundary │
│ • Stronger than standard containers │
└─────────────────────────────────────────────────────────────┘
When to Use Kata
| Scenario | Kata? |
| Regulated multi-tenant | ✅ Yes |
| Untrusted workloads | ✅ Yes |
| Internal trusted teams | ❌ Standard containers |
| Performance-critical | ⚠️ Evaluate overhead |
PART 3: PRODUCTION FAILURE MODES
14. Top 10 GPU Orchestration Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | GPU not detected | Pod Pending, no GPU resource | Driver issue | Check GPU Operator logs |
| 2 | MIG configuration failed | GPU reset error | Active processes on GPU | Stop all GPU workloads |
| 3 | Time-slicing not working | Only 1 pod per GPU | ConfigMap not applied | Update GPU Operator |
| 4 | GPU OOM | CUDA out of memory | VRAM exceeded | Reduce batch size, use MIG |
| 5 | GPU XID errors | Workload crashes | Hardware/driver fault | Check DCGM metrics |
| 6 | Noisy neighbor | Unpredictable latency | No isolation (time-slicing) | Use MIG |
| 7 | GPU quota exceeded | Pod Pending | ResourceQuota limit | Increase quota |
| 8 | Cost anomaly | Unexpected bill spike | Idle GPUs running | Monitor utilization |
| 9 | MIG profile mismatch | Pod can't schedule | Wrong MIG profile requested | Check node MIG config |
| 10 | NVLink topology ignored | Slow multi-GPU training | Default scheduler not topology-aware | Use topology-aware scheduler |
15. GPU Debugging Runbook
"GPU Pod is Pending" — Step-by-Step
text
STEP 1: Check pod status
$ kubectl describe pod <pod>
# Look at Events for scheduling failures
STEP 2: Check GPU availability
$ kubectl describe node <gpu-node> | grep nvidia.com/gpu
# How many GPUs are advertised?
STEP 3: Check GPU Operator
$ kubectl get pods -n gpu-operator
$ kubectl logs -n gpu-operator -l app=nvidia-device-plugin --tail=50
STEP 4: Check tolerations
# Does the pod tolerate the GPU node taint?
$ kubectl get pod <pod> -o jsonpath='{.spec.tolerations}'
STEP 5: Check node selector/affinity
# Does the pod match GPU node labels?
$ kubectl get pod <pod> -o jsonpath='{.spec.nodeSelector}'
$ kubectl get nodes --show-labels | grep gpu
STEP 6: Check quota
$ kubectl describe resourcequota -n <namespace>
STEP 7: Check MIG (if applicable)
# Is the requested MIG profile available?
$ kubectl describe node <gpu-node> | grep nvidia.com/mig
STEP 8: Escalate
"GPU Workload is Slow" — Step-by-Step
text
STEP 1: Check GPU utilization
$ kubectl port-forward -n gpu-operator svc/nvidia-dcgm-exporter 9400:9400
curl localhost:9400/metrics | grep DCGM_FI_DEV_GPU_UTIL
STEP 2: Check for noisy neighbors
# Are multiple pods on the same GPU?
$ kubectl get pods -A -o json | jq '.items[] | select(.spec.containers[].resources.limits."nvidia.com/gpu" != null)'
STEP 3: Check topology
# Is the workload using NVLink-connected GPUs?
$ nvidia-smi topo -m
STEP 4: Check MIG isolation
# Is the workload on a dedicated MIG instance?
$ nvidia-smi -L
STEP 5: Escalate
16. Blast Radius Analysis
What Happens When GPU Orchestration Fails?
| Component | Impact | Severity |
| GPU Operator down | New GPUs not detected | SEV-1 |
| Device plugin down | GPU pods can't schedule | SEV-1 |
| MIG misconfiguration | GPU reset required, workloads killed | SEV-1 |
| GPU hardware failure | Node unavailable | SEV-1 |
| Time-slicing without isolation | Noisy neighbor | SEV-2 |
| GPU quota exceeded | Pods Pending | SEV-3 |
| Cost anomaly | Budget overrun | SEV-3 |
Mitigation Strategies
| Strategy | Implementation |
| HA GPU Operator | Multiple replicas |
| GPU node pools | Dedicated nodes, taints |
| MIG for isolation | Hardware-level partitions |
| DCGM monitoring | Alerts on GPU health |
| Cost alerts | Budget-based alerts |
PART 4: CAPACITY PLANNING & COST MODELING
17. GPU Capacity and Utilization Modeling
GPU Capacity Formula
text
Total GPU capacity = (Number of nodes) × (GPUs per node)
Example:
- 10 nodes × 8 GPUs = 80 GPUs
- With time-slicing (4x): 320 virtual GPUs
- With MIG (7x 1g.5gb): 560 MIG instances
Utilization Metrics
| Metric | Target | Action if Below |
| GPU utilization | > 70% | Rightsize, consolidate |
| VRAM utilization | > 80% | Increase batch size |
| GPU memory | < 90% | Add capacity |
| Idle GPU hours | < 10% | Kill idle workloads |
GPU Idle Detection
promql
# Idle GPUs (utilization < 5% for 30 min)
(DCGM_FI_DEV_GPU_UTIL < 5)
and
(DCGM_FI_DEV_GPU_UTIL < 5 offset 30m)
18. GPU Cost Modeling and FinOps
GPU Cost Comparison (2026)
| GPU | Cloud On-Demand | Spot | Reserved |
| A100 40GB | $3–5/hour | $0.50–1.50/hour | $1.50–2.50/hour |
| A100 80GB | $4–7/hour | $0.80–2/hour | $2–3.50/hour |
| H100 80GB | $8–15/hour | $2–5/hour | $4–8/hour |
| H200 | $12–20/hour | $3–7/hour | $6–10/hour |
The 60% Cost Reduction Playbook
| Strategy | Savings |
| Spot instances for training | 70–91% on eligible |
| MIG for inference | 50–70% |
| Right-size GPU type | 30–50% |
| Autoscaling | Variable |
| Combined | 60%+ |
Cost Allocation
| Dimension | Example |
| Namespace | team-a, team-b |
| Label | gpu-type=h100 |
| MIG instance | 1g.5gb |
| Training job | experiment-42 |
19. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
GPU SLA Design
| Target | Architecture |
| 99.9% | Single GPU node pool, basic monitoring |
| 99.99% | Multi-node GPU pool, MIG isolation, DCGM alerts |
| 99.999% | Multi-cluster, Kata isolation, chaos-tested |
PART 5: ARCHITECTURE & STRATEGY
20. Multi-Tenant GPU Platform Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ GPU PLATFORM ARCHITECTURE │
│ │
│ Layer 1: Kubernetes │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Namespaces + RBAC + ResourceQuota │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 2: Scheduling │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ KAI Scheduler / Kueue / Volcano │ │
│ │ • Gang scheduling, fair sharing, quotas │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 3: Hardware │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ MIG / Time-slicing │ │
│ │ • Hardware isolation (MIG) │ │
│ │ • Software sharing (time-slicing) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 4: Runtime │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Kata Containers (optional) │ │
│ │ • VM-level isolation │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 5: Observability │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ DCGM Exporter + Prometheus + Grafana │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
21. GPU Fleet Management
| Component | Purpose |
| GPU Operator | Driver, device plugin, DCGM |
| Node Feature Discovery | Label GPU model |
| Karpenter | GPU node provisioning |
| KAI Scheduler | AI-aware scheduling |
| DCGM | GPU monitoring |
| Kubecost | GPU cost allocation |
22. Compliance & Security for GPU Workloads
| Framework | GPU Requirement |
| PCI-DSS | Isolated GPU (MIG), audit logs |
| HIPAA | Encrypted data, audit trails |
| SOC2 | Change management, monitoring |
| FedRAMP | FIPS 140-2, Kata isolation |
PART 6: HANDS-ON LABS
Lab 1: Install GPU Operator and Verify GPUs
bash
# Install GPU Operator
helm repo add nvidia https://helm.ngc.nvidia.com/nvidia
helm repo update
helm install gpu-operator nvidia/gpu-operator \
--namespace gpu-operator --create-namespace \
--set driver.enabled=true --wait
# Verify
kubectl get pods -n gpu-operator
kubectl get nodes -l nvidia.com/gpu.present=true
# Check GPU resources
kubectl describe node <gpu-node> | grep nvidia.com/gpu
Lab 2: Configure GPU Time-Slicing
bash
# Create ConfigMap
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
name: time-slicing-config
namespace: gpu-operator
data:
any: |
version: v1
flags:
migStrategy: none
sharing:
timeSlicing:
resources:
- name: nvidia.com/gpu
replicas: 4
EOF
# Update GPU Operator
helm upgrade gpu-operator nvidia/gpu-operator \
--namespace gpu-operator \
--set devicePlugin.config.name=time-slicing-config \
--set devicePlugin.config.default=any \
--reuse-values
# Verify
kubectl describe node <gpu-node> | grep nvidia.com/gpu
# Should show 4x capacity
Lab 3: Configure MIG Partitioning
bash
# Create MIG ConfigMap
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
name: mig-config
namespace: gpu-operator
data:
config.yaml: |
version: v1
mig-configs:
all-1g.5gb:
- devices: all
mig-enabled: true
mig-devices:
"1g.5gb": 7
EOF
# Apply
helm upgrade gpu-operator nvidia/gpu-operator \
--namespace gpu-operator \
--set migManager.config.name=mig-config \
--reuse-values
# Verify MIG
kubectl describe node <gpu-node> | grep nvidia.com/mig
Lab 4: Deploy DCGM Exporter and Monitor GPUs
bash
# DCGM is deployed by GPU Operator
kubectl get pods -n gpu-operator -l app=nvidia-dcgm-exporter
# Port-forward
kubectl port-forward -n gpu-operator svc/nvidia-dcgm-exporter 9400:9400
# Check metrics
curl localhost:9400/metrics | grep DCGM_FI_DEV_GPU_UTIL
Lab 5: GPU Multi-Tenancy
bash
kubectl create namespace team-a
kubectl create namespace team-b
# ResourceQuota for team-a
cat <<'EOF' | kubectl apply -n team-a -f -
apiVersion: v1
kind: ResourceQuota
metadata:
name: gpu-quota
spec:
hard:
requests.nvidia.com/gpu: "2"
limits.nvidia.com/gpu: "2"
EOF
# Deploy GPU pod in team-a
cat <<'EOF' | kubectl apply -n team-a -f -
apiVersion: v1
kind: Pod
metadata:
name: gpu-pod
spec:
containers:
- name: app
image: nvidia/cuda:12.0-base
command: ["nvidia-smi"]
resources:
limits:
nvidia.com/gpu: 1
EOF
Lab 6: GPU Cost Optimization
yaml
# Spot node pool
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: gpu-spot
spec:
template:
spec:
requirements:
- key: karpenter.sh/capacity-type
operator: In
values: ["spot"]
- key: node.kubernetes.io/instance-type
operator: In
values: ["p4d.24xlarge"]
limits:
nvidia.com/gpu: 8
Lab 7: Schedule GPU Workloads
yaml
apiVersion: v1
kind: Pod
metadata:
name: gpu-training
spec:
tolerations:
- key: nvidia.com/gpu
operator: Exists
effect: NoSchedule
nodeSelector:
nvidia.com/gpu.product: NVIDIA-A100-SXM4-40GB
containers:
- name: training
image: pytorch/pytorch:2.0-cuda11.7
resources:
limits:
nvidia.com/gpu: 4
Lab 8: Debug GPU Scheduling Failures
bash
# Create a pod requesting too many GPUs
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: impossible-gpu
spec:
containers:
- name: app
image: nvidia/cuda:12.0-base
resources:
limits:
nvidia.com/gpu: 100
EOF
sleep 10
kubectl describe pod impossible-gpu | grep -A10 Events
# Cleanup
kubectl delete pod impossible-gpu
Lab 9: End-to-End GPU Inference Platform
bash
# Deploy vLLM with GPU
cat <<'EOF' | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
name: vllm
spec:
replicas: 1
selector:
matchLabels:
app: vllm
template:
metadata:
labels:
app: vllm
spec:
containers:
- name: vllm
image: vllm/vllm-openai:latest
args: ["--model", "meta-llama/Llama-2-7b-hf"]
resources:
limits:
nvidia.com/gpu: 1
ports:
- containerPort: 8000
---
apiVersion: v1
kind: Service
metadata:
name: vllm
spec:
selector:
app: vllm
ports:
- port: 8000
EOF
# Test
kubectl port-forward svc/vllm 8000:8000
curl http://localhost:8000/v1/models
PART 7: INCIDENT MANAGEMENT
32. GPU Incident Post-Mortem Template
text
INCIDENT: GPU Node Failure - Training Job Lost
DATE: 2024-01-15
DURATION: 4 hours
SEVERITY: SEV-2
IMPACT: Training job lost 12 hours of progress. No checkpoint.
TIMELINE:
14:00 - GPU XID error detected by DCGM
14:05 - GPU node unhealthy
14:10 - Training job killed
14:15 - On-call acknowledged
14:30 - Node drained
14:45 - Replacement node provisioned
15:00 - Training restarted from last checkpoint
18:00 - Training caught up
ROOT CAUSE:
GPU hardware failure (XID 48). Training job had no checkpointing.
LESSONS LEARNED:
1. Checkpointing must be enforced for training jobs.
2. DCGM alerts must fire on XID errors.
3. Spot instances need graceful handling.
ACTION ITEMS:
[ ] Enforce checkpointing (Owner: ML Team)
[ ] Add DCGM XID alerts (Owner: SRE)
[ ] Test GPU failover (Owner: Platform)
33. On-Call Runbook: GPU Failures
text
STEP 1: Check GPU health
$ kubectl get nodes -l nvidia.com/gpu.present=true
$ kubectl describe node <gpu-node> | grep -A5 "nvidia.com/gpu"
STEP 2: Check DCGM metrics
$ kubectl port-forward -n gpu-operator svc/nvidia-dcgm-exporter 9400:9400
curl localhost:9400/metrics | grep -E "XID|TEMP|UTIL"
STEP 3: Check GPU Operator
$ kubectl get pods -n gpu-operator
$ kubectl logs -n gpu-operator -l app=nvidia-device-plugin --tail=100
STEP 4: Check MIG status
$ kubectl exec -it <gpu-pod> -- nvidia-smi -L
STEP 5: If GPU is faulty
# Cordon and drain
$ kubectl cordon <gpu-node>
$ kubectl drain <gpu-node> --ignore-daemonsets --delete-emptydir-data
STEP 6: Escalate
34. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | All GPU nodes down / GPU Operator failure | 5 min | On-call + Platform + ML Team |
| SEV-2 | Single GPU node failure / MIG corruption | 15 min | On-call + Platform |
| SEV-3 | GPU performance degradation | 1 hour | On-call |
| SEV-4 | GPU cost anomaly | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
35. Junior-Level Questions
| Question | Expected Answer |
| What is the NVIDIA Device Plugin? | Exposes GPUs to Kubernetes |
| How are GPUs requested? | nvidia.com/gpu: 1 in limits |
| What is MIG? | Hardware GPU partitioning |
| What is time-slicing? | Software GPU sharing |
| What is DCGM? | GPU monitoring and telemetry |
36. Mid-Level Questions
| Question | Expected Answer |
| Time-slicing vs MIG? | Time-slicing = no isolation; MIG = hardware isolation |
| What is GPU Operator? | Manages drivers, device plugin, DCGM |
| How do you monitor GPUs? | DCGM Exporter + Prometheus |
| What is KAI Scheduler? | AI-aware scheduling (gang, fair share) |
| How do you isolate GPU tenants? | Namespaces + MIG + quotas |
37. Senior-Level Questions
| Question | Expected Answer |
| How do you choose between MIG and time-slicing? | MIG for production isolation; time-slicing for dev |
| How do you optimize GPU costs? | Spot, MIG, right-sizing, autoscaling |
| What is DRA for GPUs? | Dynamic Resource Allocation (attribute-based) |
| How do you handle GPU failures? | DCGM alerts, checkpointing, node replacement |
| What is topology-aware scheduling? | NVLink/NVSwitch awareness |
38. Staff/Principal Questions
| Question | Expected Answer |
| Design a multi-tenant GPU platform. | Namespaces + MIG + KAI Scheduler + Kata + DCGM |
| How do you achieve 60% GPU cost reduction? | Spot + MIG + right-sizing + autoscaling |
| How do you handle GPU fleet management? | GPU Operator + Karpenter + DCGM + Kubecost |
| How do you isolate hostile GPU tenants? | Kata Containers + MIG + separate clusters |
| How do you migrate from device plugin to DRA? | Gradual, extended resource fallback |
Summary Cheat Sheet
| Concept | Key Takeaway |
| NVIDIA Device Plugin | Exposes GPUs as nvidia.com/gpu |
| GPU Operator | Manages drivers, plugin, DCGM |
| Time-Slicing | Software sharing, no isolation |
| MPS | CUDA concurrency, limited isolation |
| MIG | Hardware partitioning, full isolation |
| MIG Profiles | 1g.5gb, 2g.10gb, 3g.20gb, 7g.40gb |
| NVLink/NVSwitch | High-speed GPU interconnect |
| Topology-Aware | KubeNexus, HAMi, KAI Scheduler |
| DRA | Dynamic Resource Allocation (future) |
| DCGM | GPU monitoring (utilization, temp, errors) |
| GPU Multi-Tenancy | Namespaces + MIG + quotas + Kata |
| KAI Scheduler | Gang scheduling, fair share (CNCF Sandbox) |
| Kueue | Job queueing with quotas |
| Volcano | Batch/AI scheduling |
| Spot Instances | 70–91% savings for training |
| Cost Optimization | Spot + MIG + right-sizing + autoscaling |
| Kata Containers | VM-level GPU isolation |
Stage 13: AI/ML Workload Orchestration — The Comprehensive Guide
PART 1: CORE THEORY
1. Why Default Kubernetes Fails at AI/ML
The default Kubernetes scheduler was designed for stateless web services. It places pods individually, treats GPUs as integer resources, and has no concept of distributed job coordination. This creates three fundamental problems for AI/ML workloads.
The Three Failures
| Failure | What Happens | Impact |
| Individual Pod Placement | Distributed training pods scheduled one by one | Partial placement wastes GPUs while workers wait for peers |
| No Gang Scheduling | 4 GPUs available, 16-worker job needs 16 | 4 workers start, hold GPUs, wait forever for 12 more |
| No Team Fairness | One team's jobs starve another's | No quota enforcement, no fair sharing |
The GPU Waste Problem
Kubex found that in a Kubernetes inference environment with hundreds of GPUs, only about 20% of containers were using their full GPU allocation at any given time. The large majority were consuming less than half.
The Solution Stack
text
┌─────────────────────────────────────────────────────────────┐
│ AI WORKLOAD ORCHESTRATION │
│ │
│ Layer 1: Admission & Quota │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Kueue — Job admission, quota, fair sharing │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 2: Gang Scheduling │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Volcano / KAI Scheduler — All-or-nothing placement │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 3: Inference Engines │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ vLLM / TGI / Triton — Continuous batching, KV-cache│ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 4: Autoscaling │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ KEDA / Knative — Queue-depth-based scaling │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 5: Routing │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ llm-d / Gateway API — KV-cache-aware routing │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
2. Gang Scheduling
Gang scheduling treats a group of pods as a single scheduling unit. Either the required minimum number of pods can be scheduled together, or the entire group waits.
Why Gang Scheduling Matters
Distributed training jobs (PyTorch DDP, TensorFlow, MPI) require all workers running simultaneously. If only 4 of 16 workers start:
- The 4 running workers hold their GPUs
- They wait for the remaining 12 workers
- The 12 can't schedule because GPUs are held
- Deadlock
How Gang Scheduling Works
text
Without Gang Scheduling: With Gang Scheduling:
Worker 1 → GPU 1 (running) Worker 1-16 → Need 16 GPUs
Worker 2 → GPU 2 (running) 16 available → All 16 scheduled ✅
Worker 3 → GPU 3 (running) 8 available → None scheduled ❌
Worker 4 → GPU 4 (running) (8 held for later)
Worker 5 → Pending
Worker 6 → Pending No GPUs wasted.
... No deadlock.
Deadlock.
The PodGroup Concept
Gang scheduling uses a PodGroup (Volcano) or Workload (Kueue) to group pods:
yaml
apiVersion: scheduling.volcano.sh/v1beta1
kind: PodGroup
metadata:
name: pytorch-training
spec:
minMember: 16 # Minimum pods to schedule
minResources:
nvidia.com/gpu: "16"
queue: training-queue
Gang Scheduling Tools
| Tool | Approach | CNCF Status |
| Volcano | Full batch scheduling ecosystem | Incubating |
| KAI Scheduler | NVIDIA AI-aware scheduler | Sandbox |
| Kueue | Admission + gang via integration | Incubating |
| Coscheduling | Scheduler plugin | Kubernetes SIG |
3. Kueue
Kueue is a Kubernetes-native job queueing system. It decides when supported workloads wait, receive admission, or are preempted according to quota and policy. It leaves pod-to-node placement to the Kubernetes scheduling layer.
The Separation of Concerns
| Layer | Responsibility | Tool |
| Admission | Should this job run now? | Kueue |
| Placement | Which node should this pod go to? | kube-scheduler / Volcano / KAI |
Kueue decides when a job runs, not where its pods land.
Kueue Resources
| Resource | Scope | Purpose |
| ResourceFlavor | Cluster | Defines available resource types |
| ClusterQueue | Cluster | Defines quota pool |
| LocalQueue | Namespace | Submission entry point |
| Workload | Namespace | Represents a job's resource needs |
| Cohort | Cluster | Groups queues for quota borrowing |
Kueue Example
yaml
apiVersion: kueue.x-k8s.io/v1beta2
kind: ResourceFlavor
metadata:
name: gpu-flavor
---
apiVersion: kueue.x-k8s.io/v1beta2
kind: ClusterQueue
metadata:
name: gpu-queue
spec:
namespaceSelector: {}
resourceGroups:
- coveredResources: ["nvidia.com/gpu"]
flavors:
- name: gpu-flavor
resources:
- name: nvidia.com/gpu
nominalQuota: 32
---
apiVersion: kueue.x-k8s.io/v1beta2
kind: LocalQueue
metadata:
name: team-a-queue
namespace: team-a
spec:
clusterQueue: gpu-queue
When to Use Kueue
| Scenario | Kueue? |
| Multi-team GPU sharing | ✅ Yes |
| Job queueing with quotas | ✅ Yes |
| Fair-share admission | ✅ Yes |
| Single-team cluster | ❌ Default scheduler |
| Simple inference | ❌ KEDA/HPA |
4. Volcano
Volcano is a CNCF incubating project that brings gang scheduling, queue-based resource policies, and placement options to batch workloads.
Volcano Architecture
| Component | Purpose |
| Volcano Scheduler | Gang scheduling, fair-share, topology |
| Volcano Controller | Job lifecycle management |
| PodGroup | Group of pods scheduled together |
| Queue | Resource pool with quota |
Volcano vs Kueue
| Aspect | Volcano | Kueue |
| Primary role | Batch scheduling | Admission control |
| Gang scheduling | ✅ Native | ✅ Via integration |
| Queue model | Volcano Queue | ClusterQueue + LocalQueue |
| Job controller | Volcano Job (vcjob) | Kubernetes Job |
| CNCF Status | Incubating | Incubating |
Key distinction: Volcano replaces the scheduler. Kueue works alongside the existing scheduler, managing admission only.
Volcano Job Example
yaml
apiVersion: batch.volcano.sh/v1alpha1
kind: Job
metadata:
name: pytorch-training
spec:
minAvailable: 16
schedulerName: volcano
queue: training-queue
policies:
- event: PodEvicted
action: RestartJob
tasks:
- replicas: 16
name: worker
template:
spec:
containers:
- name: pytorch
image: pytorch/pytorch:2.0-cuda11.7
resources:
limits:
nvidia.com/gpu: 1
When to Use Volcano
| Scenario | Volcano? |
| Distributed training | ✅ Yes |
| Batch AI jobs | ✅ Yes |
| Gang scheduling | ✅ Yes |
| Simple inference | ❌ KEDA/HPA |
| Existing scheduler | ⚠️ Can coexist |
PART 2: ADVANCED CONCEPTS
5. vLLM
vLLM is the de-facto industry standard for high-throughput LLM inference. It combines PagedAttention and continuous batching to maximize GPU utilization.
PagedAttention
Traditional LLM serving allocates KV cache as one contiguous block per sequence. This wastes 60–80% of GPU memory due to fragmentation.
PagedAttention stores KV blocks in a paged table — memory is allocated per token-block rather than per whole sequence. This is what makes high occupancy and large effective concurrency possible.
text
Traditional: PagedAttention:
Sequence A: [████████░░░░░░░░] Block table:
Sequence B: [████░░░░░░░░░░░░] Seq A → [B1][B2][B3]
Sequence C: [██████░░░░░░░░░░] Seq B → [B4][B5]
Seq C → [B6][B7][B8]
Wasted: ~70% Wasted: ~4%
Continuous Batching
Traditional batching waits for all sequences to finish before starting new ones. GPU sits idle while waiting for the longest sequence — utilization ~40–60%.
Continuous batching adds new requests as slots become available, mixing prefill (new requests) and decode (ongoing) in the same batch.
text
Traditional Batching: Continuous Batching:
Time → Time →
[Req1][Req2][Req3] [Req1][Req4][Req7]
Wait for all to finish [Req2][Req5][Req8]
[Req4][Req5][Req6] [Req3][Req6][Req9]
GPU idle between batches GPU never idle
vLLM Deployment on Kubernetes
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: vllm
spec:
replicas: 1
selector:
matchLabels:
app: vllm
template:
metadata:
labels:
app: vllm
spec:
containers:
- name: vllm
image: vllm/vllm-openai:latest
args:
- "--model"
- "meta-llama/Llama-2-7b-hf"
- "--tensor-parallel-size"
- "1"
- "--max-model-len"
- "4096"
resources:
limits:
nvidia.com/gpu: 1
requests:
cpu: 4
memory: 16Gi
ports:
- containerPort: 8000
readinessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 60
periodSeconds: 10
vLLM Performance
Real-world benchmarks show vLLM achieving 2–24x throughput compared to naive implementations. Stripe achieved a 73% reduction in inference costs by migrating to vLLM for 50 million daily API calls with one-third of the fleet.
Key vLLM Flags
| Flag | Purpose |
--tensor-parallel-size | Number of GPUs for tensor parallelism |
--max-model-len | Maximum sequence length |
--gpu-memory-utilization | Fraction of GPU memory to use (default 0.9) |
--enable-prefix-caching | Enable KV-cache prefix reuse |
--quantization | Quantization method (awq, gptq, fp8) |
6. TGI (Text Generation Inference)
TGI is Hugging Face's production inference server. It includes tensor parallelism, quantization, continuous batching, and token streaming.
TGI Features
| Feature | Purpose |
| Continuous batching | Dynamic request grouping for better GPU utilization |
| Token streaming | Better UX for long responses |
| Tensor parallelism | Multi-GPU model sharding |
| Quantization | Reduce memory footprint |
| Flash Attention | Faster attention computation |
TGI Deployment on Kubernetes
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: tgi
spec:
replicas: 1
selector:
matchLabels:
app: tgi
template:
metadata:
labels:
app: tgi
spec:
containers:
- name: tgi
image: ghcr.io/huggingface/text-generation-inference:latest
args:
- "--model-id"
- "meta-llama/Llama-2-7b-chat-hf"
- "--num-shard"
- "1"
- "--max-batch-prefill-tokens"
- "4096"
- "--max-batch-total-tokens"
- "8192"
resources:
limits:
nvidia.com/gpu: 1
ports:
- containerPort: 80
TGI Best Practices
| Practice | Why |
Set --num-shard = GPU count | Prevent OOMKill mid-request |
Tune --max-batch-prefill-tokens | Control prefill memory |
Tune --max-batch-total-tokens | Control total batch memory |
| Use A10 or newer | TGI does not support V100 or T4 |
Critical: Kubernetes requests.nvidia.com/gpu must match --num-shard count, not total GPU count. If you set num-shard=4 but request only 2 GPUs, the pod will OOMKill mid-request.
TGI vs vLLM
| Aspect | TGI | vLLM |
| Backed by | Hugging Face | vLLM project |
| Continuous batching | ✅ | ✅ |
| PagedAttention | ❌ (uses different memory management) | ✅ |
| Tensor parallelism | ✅ | ✅ |
| Streaming | ✅ | ✅ |
| Ecosystem | Hugging Face | OpenAI-compatible |
7. Triton Inference Server
NVIDIA Triton Inference Server is a multi-framework inference server. It supports TensorRT, PyTorch, ONNX, TensorFlow, and vLLM as a backend.
Triton with vLLM Backend
Triton's vLLM backend combines Triton's multi-model management with vLLM's PagedAttention and continuous batching.
Triton Deployment
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: triton
spec:
replicas: 1
selector:
matchLabels:
app: triton
template:
metadata:
labels:
app: triton
spec:
containers:
- name: triton
image: nvcr.io/nvidia/tritonserver:24.01-trtllm-python-py3
args:
- "--model-repository=/models"
- "--model-control-mode=explicit"
resources:
limits:
nvidia.com/gpu: 1
ports:
- containerPort: 8000 # HTTP
- containerPort: 8001 # gRPC
- containerPort: 8002 # Metrics
Triton Model Repository
text
/models
├── llama-2-7b
│ ├── config.pbtxt
│ └── 1/
│ └── model.py
└── bert
├── config.pbtxt
└── 1/
└── model.onnx
When to Use Triton
| Scenario | Triton? |
| Multi-framework | ✅ Yes |
| Enterprise deployment | ✅ Yes |
| LLM-only | ⚠️ vLLM direct is simpler |
| Multi-model serving | ✅ Yes |
| Simple LLM | ❌ vLLM direct |
8. KV-Cache Management and Offloading
The KV cache is the invisible state that every LLM request carries. Hit it, and your response is 10x cheaper and 50x faster. Miss it, and you're recomputing work you just did.
The KV-Cache Problem
| Scenario | Impact |
| Cache hit | 10x cheaper, 50x faster |
| Cache miss | Full recomputation |
| Cache-blind routing | Scatters related requests, destroys locality |
Tiered KV-Cache
Google Cloud's approach extends KV-cache from NVIDIA GPU HBM (Tier 1) to CPU RAM and local SSDs (Tier 2).
text
Tier 1: GPU HBM (fastest, smallest)
Tier 2: CPU RAM (medium speed, larger)
Tier 3: Local NVMe SSD (slower, largest)
LMCache
LMCache extends the KV cache from GPU HBM to CPU RAM and local SSDs, dramatically increasing total cache size.
yaml
# vLLM with LMCache
env:
- name: VLLM_USE_LMCACHE
value: "1"
- name: LMCACHE_BACKEND
value: "local_disk"
When to Use KV-Cache Offloading
| Scenario | Offloading? |
| Long context | ✅ Yes |
| Multi-turn chat | ✅ Yes |
| RAG pipelines | ✅ Yes |
| Short prompts | ❌ No benefit |
| Single-turn QA | ❌ No benefit |
9. Inference Autoscaling
Traditional HPA based on CPU and memory may respond too slowly for LLM inference. KEDA enables direct SLO-driven scaling by leveraging actual SLIs like Inter-Token Latency (ITL) and end-to-end response times from vLLM.
vLLM Metrics for Autoscaling
| Metric | Meaning | Use |
num_requests_waiting | Queue depth | Scale up trigger |
num_requests_running | Active requests | Utilization |
inter_token_latency | Time between tokens | SLO metric |
time_to_first_token | TTFT | User experience |
KEDA ScaledObject for vLLM
yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: vllm-scaler
spec:
scaleTargetRef:
name: vllm
minReplicaCount: 1
maxReplicaCount: 10
pollingInterval: 15
cooldownPeriod: 300
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus:9090
metricName: num_requests_waiting
threshold: "5"
query: |
sum(vllm:num_requests_waiting)
Scaling Behavior
| Action | Time |
| Scale up | ~30–60 seconds |
| Scale down | ~5 minute cooldown |
Knative vs KEDA
| Aspect | Knative | KEDA |
| Scaling metric | Request concurrency | Custom metrics |
| Scale to zero | ✅ Yes | ✅ (with HTTP add-on) |
| Cold start | Higher | Lower |
| SLO-driven | ❌ | ✅ |
| Best for | Serverless inference | Production inference |
10. Model Caching and Warm Pools
Cold start is the biggest UX problem in AI inference. A model that takes 5 minutes to load will fail autoscaling.
Cold Start Decomposition
The startup path has six phases:
| Phase | Time | Optimization |
| T_capacity | Node provisioning | Karpenter, warm pools |
| T_schedule | Pod scheduling | Node affinity |
| T_image | Image pull | Image pre-warming |
| T_model | Model weight loading | Local NVMe cache |
| T_runtime | Runtime initialization | Pre-built runtime |
| T_warmup | GPU warmup | Warm pools |
KServe LocalModelCache
KServe's LocalModelCache caches models on Kubernetes nodes' local NVMe volumes.
yaml
apiVersion: serving.kserve.io/v1alpha1
kind: LocalModelCache
metadata:
name: llama-cache
spec:
sourceModelUri: "hf://meta-llama/Llama-2-7b-hf"
nodeGroups:
- gpu-node-group
persistentVolumeClaim: llama-model-pvc
Warm Pools
Warm pools keep pre-loaded model instances ready for immediate traffic. The trade-off is cost: idle GPUs in the warm pool still cost money.
| Strategy | Cold Start | Cost |
| No warm pool | 5 min | Lowest |
| 1 warm replica | <10 sec | Medium |
| Full warm pool | <1 sec | Highest |
Model Caching Strategies
| Strategy | Cold Start | Cost |
| Hugging Face Hub | 5+ min | $ |
| Local NVMe cache | 30 sec | $$ |
| Warm pool | <10 sec | $$$ |
11. Cache-Aware Routing
Kubernetes' default load balancing is cache-blind, scattering related requests across pods and destroying locality. This makes AI workloads slower and vastly more expensive than they should be.
The Problem
text
Request 1 (User A, prompt X) → Pod 1 (cache miss, 5s)
Request 2 (User A, prompt X) → Pod 2 (cache miss, 5s)
Request 3 (User A, prompt X) → Pod 3 (cache miss, 5s)
3x work, 3x latency, 3x cost
The Solution: llm-d
llm-d is a Kubernetes-native framework for distributed LLM inference with an AI-aware scheduler. It uses KV-cache-aware routing to direct requests to pods that already hold relevant context in GPU memory.
Gateway API Inference Extension
The Gateway API Inference Extension replaces the default Service with AI-aware routing.
yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: llm-route
spec:
parentRefs:
- name: inference-gateway
rules:
- matches:
- path:
type: PathPrefix
value: /v1
backendRefs:
- name: vllm-pods
kind: Service
port: 8000
When to Use Cache-Aware Routing
| Scenario | Cache-Aware? |
| Multi-turn chat | ✅ Yes |
| RAG pipelines | ✅ Yes |
| Long system prompts | ✅ Yes |
| Single-turn QA | ❌ No benefit |
| Unique prompts | ❌ No benefit |
12. KAI Scheduler
KAI Scheduler is NVIDIA's open-source, Kubernetes-native scheduler for AI workloads. It provides GPU-oriented placement, grouping, and resource-sharing policy.
KAI Scheduler Capabilities
| Capability | Purpose |
| Gang scheduling | All-or-nothing placement |
| Hierarchical queues | Team quotas with DRF |
| GPU sharing | Fractional GPU support |
| Topology-aware placement | NVLink/NVSwitch awareness |
| Workload priority and preemption | Critical job priority |
HAMi GPU Hard Isolation
In June 2026, HAMi's GPU memory hard isolation shipped as a built-in feature of KAI Scheduler. This provides memory-level isolation for shared GPUs without requiring MIG.
KAI Scheduler Use Cases
| Use Case | KAI? |
| Multi-team GPU sharing | ✅ Yes |
| Distributed training | ✅ Yes |
| Inference with sharing | ✅ Yes |
| Single-team cluster | ❌ Default scheduler |
PART 3: PRODUCTION FAILURE MODES
13. Top 10 AI/ML Orchestration Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | Distributed training deadlock | All pods Pending | No gang scheduling | Use Volcano/KAI |
| 2 | Cold start timeout | Autoscaling fails | Model loading takes 5+ min | Model caching, warm pool |
| 3 | KV-cache miss storm | High latency, low throughput | Cache-blind routing | llm-d, Gateway API |
| 4 | GPU OOMKill | Pod killed mid-request | Model + KV-cache exceeds VRAM | Reduce batch size, quantize |
| 5 | KEDA metric unavailable | Autoscaling stuck | Prometheus scrape failure | Fix ServiceMonitor |
| 6 | Model cache stale | Wrong model served | Cache not invalidated | Version cache keys |
| 7 | Gang scheduling deadlock | Pods Pending forever | minMember > available GPUs | Reduce workers, add GPUs |
| 8 | Queue starvation | One team monopolizes GPU | No fair-share policy | Kueue/KAI queues |
| 9 | Tensor parallel mismatch | OOMKill mid-request | num-shard > GPU count | Match num-shard to GPUs |
| 10 | Cache-aware routing misconfigured | No cache hits | Wrong routing policy | Tune llm-d policies |
14. AI Workload Debugging Runbook
"Distributed Training Job is Deadlocked" — Step-by-Step
text
STEP 1: Check job status
$ kubectl get pods -l job-name=<job>
# Look for Pending pods
STEP 2: Check PodGroup/Workload status
$ kubectl get podgroup <name> -o yaml
# Check minMember vs scheduled
STEP 3: Check GPU availability
$ kubectl describe nodes | grep -A5 "nvidia.com/gpu"
STEP 4: Check gang scheduling
$ kubectl get job <name> -o yaml | grep schedulerName
# Should be "volcano" or "kai-scheduler"
STEP 5: Check queue status
$ kubectl get queue -o yaml
STEP 6: Check for resource deadlock
# How many GPUs needed? How many available?
# If needed > available → deadlock
STEP 7: Fix
# Option A: Reduce workers
# Option B: Add GPUs
# Option C: Check other jobs holding GPUs
STEP 8: Escalate
"Inference Latency is High" — Step-by-Step
text
STEP 1: Check GPU utilization
$ kubectl port-forward -n gpu-operator svc/nvidia-dcgm-exporter 9400:9400
curl localhost:9400/metrics | grep DCGM_FI_DEV_GPU_UTIL
STEP 2: Check vLLM queue depth
$ kubectl port-forward svc/vllm 8000:8000
curl localhost:8000/metrics | grep num_requests_waiting
STEP 3: Check KV-cache hit rate
curl localhost:8000/metrics | grep prefix_cache_hit
STEP 4: Check routing
# Is traffic going to the same pod?
$ kubectl get endpoints vllm
STEP 5: Check model caching
# Is the model cached locally?
$ kubectl exec -it <vllm-pod> -- ls /models
STEP 6: Escalate
15. Blast Radius Analysis
What Happens When AI Orchestration Fails?
| Component | Impact | Severity |
| Gang scheduling failure | All distributed training deadlocked | SEV-1 |
| Inference engine down | All LLM requests fail | SEV-1 |
| KEDA down | No autoscaling, capacity fixed | SEV-2 |
| KV-cache routing failure | 10x latency, 10x cost | SEV-2 |
| Model cache corruption | Wrong model served | SEV-1 |
| Queue starvation | One team blocks others | SEV-2 |
| Cold start timeout | Autoscaling ineffective | SEV-2 |
Mitigation Strategies
| Strategy | Implementation |
| Gang scheduling | Volcano or KAI Scheduler |
| Model caching | Local NVMe, warm pools |
| Cache-aware routing | llm-d, Gateway API |
| KEDA autoscaling | Queue-depth metrics |
| Queue fairness | Kueue, KAI queues |
| GPU monitoring | DCGM, Prometheus |
PART 4: CAPACITY PLANNING & COST MODELING
16. GPU Utilization and Cost Modeling
GPU Utilization Targets
| Metric | Target | Action if Below |
| GPU utilization | > 70% | Rightsize, consolidate |
| KV-cache hit rate | > 50% | Cache-aware routing |
| Queue depth | < 5 | Scale up |
| Batch size | Maximize | Tune continuous batching |
Cost Per Token
The optimization goal for inference is cost per token:
text
Cost per token = (GPU cost per hour) / (Tokens per hour)
Example:
- A100: $3/hour
- Throughput: 10,000 tokens/second
- Tokens per hour: 36M
- Cost per token: $3 / 36M = $0.000000083
Optimization Playbook
| Strategy | Savings |
| vLLM vs naive | 2–24x throughput |
| Continuous batching | 2–4x |
| PagedAttention | 2–4x memory efficiency |
| KV-cache offloading | 30–50% |
| Cache-aware routing | 10x on cache hits |
| Quantization | 2x memory reduction |
17. Cost Per Token Optimization
The Four Levers
| Lever | Impact | Effort |
| Inference engine | 2–24x | Low |
| Batching | 2–4x | Low |
| KV-cache | 10x on hits | Medium |
| Hardware | 2–3x | High |
Real-World Results
| Company | Result |
| Stripe | 73% cost reduction with vLLM (50M daily calls, 1/3 fleet) |
| Google Cloud | Tiered KV-cache extends effective cache size |
| Kubex | 80% of containers underutilizing GPU allocation |
18. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
AI Workload SLA Design
| Target | Architecture |
| 99.9% | Single inference replica, basic monitoring |
| 99.99% | Multiple replicas, KEDA autoscaling, model caching |
| 99.999% | Multi-region, warm pools, cache-aware routing, chaos-tested |
Cold Start SLA
| Strategy | Cold Start | SLA Impact |
| No caching | 5 min | ❌ Autoscaling fails |
| Local NVMe | 30 sec | ⚠️ Slow but works |
| Warm pool | <10 sec | ✅ Acceptable |
| Always-on | 0 sec | ✅ Best but costly |
PART 5: ARCHITECTURE & STRATEGY
19. End-to-End AI Platform Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ AI PLATFORM ARCHITECTURE │
│ │
│ Layer 1: Admission & Quota │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Kueue — ClusterQueue, LocalQueue, Cohort │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 2: Gang Scheduling │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Volcano / KAI Scheduler — PodGroup, Queue │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 3: Inference Engine │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ vLLM / TGI / Triton — PagedAttention, batching │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 4: Autoscaling │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ KEDA — Queue depth, SLO-driven │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 5: Model Caching │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ KServe LocalModelCache, Warm Pools │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 6: Cache-Aware Routing │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ llm-d, Gateway API Inference Extension │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
20. Multi-Tenant AI Platform Design
| Tenant Type | Isolation | Tool |
| Internal teams | Namespaces + Kueue queues | Kueue |
| External customers | vCluster + MIG | vCluster |
| Regulated | Kata Containers + MIG | Kata |
| Hostile | Separate clusters | — |
Multi-Tenant Queue Design
yaml
apiVersion: kueue.x-k8s.io/v1beta2
kind: Cohort
metadata:
name: ai-cohort
spec:
resourceGroups:
- coveredResources: ["nvidia.com/gpu"]
flavors:
- name: a100
resources:
- name: nvidia.com/gpu
nominalQuota: 64
21. Compliance & Security for AI Workloads
| Framework | AI Requirement |
| PCI-DSS | Isolated GPU, audit logs |
| HIPAA | Encrypted model/data, audit |
| SOC2 | Change management, monitoring |
| GDPR | Data residency |
| EU AI Act | Model documentation, audit trails |
PART 6: HANDS-ON LABS
Lab 1: Install Kueue and Create a ClusterQueue
bash
# Install Kueue
kubectl apply -f https://github.com/kubernetes-sigs/kueue/releases/download/v0.10.0/manifests.yaml
# Create ResourceFlavor
cat <<'EOF' | kubectl apply -f -
apiVersion: kueue.x-k8s.io/v1beta2
kind: ResourceFlavor
metadata:
name: default-flavor
---
apiVersion: kueue.x-k8s.io/v1beta2
kind: ClusterQueue
metadata:
name: cluster-queue
spec:
namespaceSelector: {}
resourceGroups:
- coveredResources: ["cpu", "memory", "nvidia.com/gpu"]
flavors:
- name: default-flavor
resources:
- name: cpu
nominalQuota: 100
- name: memory
nominalQuota: 200Gi
- name: nvidia.com/gpu
nominalQuota: 4
---
apiVersion: kueue.x-k8s.io/v1beta2
kind: LocalQueue
metadata:
name: user-queue
namespace: default
spec:
clusterQueue: cluster-queue
EOF
# Verify
kubectl get clusterqueue,localqueue
Lab 2: Gang Scheduling with Volcano
bash
# Install Volcano
helm repo add volcano-sh https://volcano-sh.github.io/helm-charts
helm install volcano volcano-sh/volcano -n volcano-system --create-namespace
# Create a gang-scheduled Job
cat <<'EOF' | kubectl apply -f -
apiVersion: batch.volcano.sh/v1alpha1
kind: Job
metadata:
name: gang-job
spec:
minAvailable: 3
schedulerName: volcano
tasks:
- replicas: 3
name: worker
template:
spec:
containers:
- name: worker
image: busybox
command: ["sh", "-c", "echo Worker; sleep 3600"]
resources:
requests:
cpu: 100m
EOF
# Check status
kubectl get pods -l volcano.sh/job-name=gang-job
kubectl get podgroup gang-job -o yaml
Lab 3: Deploy vLLM for LLM Inference
bash
# Deploy vLLM
cat <<'EOF' | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
name: vllm
spec:
replicas: 1
selector:
matchLabels:
app: vllm
template:
metadata:
labels:
app: vllm
spec:
containers:
- name: vllm
image: vllm/vllm-openai:latest
args: ["--model", "facebook/opt-125m"]
resources:
limits:
nvidia.com/gpu: 1
ports:
- containerPort: 8000
EOF
# Wait for ready
kubectl wait --for=condition=Available deployment/vllm --timeout=300s
# Test
kubectl port-forward svc/vllm 8000:8000 &
sleep 2
curl http://localhost:8000/v1/completions \
-H "Content-Type: application/json" \
-d '{"model": "facebook/opt-125m", "prompt": "Hello", "max_tokens": 10}'
kill %1
Lab 4: Deploy TGI on Kubernetes
bash
cat <<'EOF' | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
name: tgi
spec:
replicas: 1
selector:
matchLabels:
app: tgi
template:
metadata:
labels:
app: tgi
spec:
containers:
- name: tgi
image: ghcr.io/huggingface/text-generation-inference:latest
args: ["--model-id", "facebook/opt-125m", "--num-shard", "1"]
resources:
limits:
nvidia.com/gpu: 1
ports:
- containerPort: 80
EOF
kubectl wait --for=condition=Available deployment/tgi --timeout=300s
kubectl port-forward svc/tgi 8080:80 &
sleep 2
curl http://localhost:8080/generate \
-H "Content-Type: application/json" \
-d '{"inputs": "Hello", "parameters": {"max_new_tokens": 10}}'
kill %1
Lab 5: Deploy Triton Inference Server
bash
cat <<'EOF' | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
name: triton
spec:
replicas: 1
selector:
matchLabels:
app: triton
template:
metadata:
labels:
app: triton
spec:
containers:
- name: triton
image: nvcr.io/nvidia/tritonserver:24.01-py3
args: ["--model-repository=/models"]
resources:
limits:
nvidia.com/gpu: 1
ports:
- containerPort: 8000
EOF
kubectl wait --for=condition=Available deployment/triton --timeout=300s
kubectl port-forward svc/triton 8000:8000 &
sleep 2
curl http://localhost:8000/v2/health/ready
kill %1
Lab 6: Configure KEDA Autoscaling for vLLM
bash
# Install KEDA
helm repo add kedacore https://kedacore.github.io/charts
helm install keda kedacore/keda -n keda --create-namespace
# Create ScaledObject
cat <<'EOF' | kubectl apply -f -
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: vllm-scaler
spec:
scaleTargetRef:
name: vllm
minReplicaCount: 1
maxReplicaCount: 5
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus:9090
metricName: num_requests_waiting
threshold: "5"
query: sum(vllm:num_requests_waiting)
EOF
# Check HPA
kubectl get hpa
Lab 7: Model Caching with KServe
yaml
apiVersion: serving.kserve.io/v1alpha1
kind: LocalModelCache
metadata:
name: llama-cache
spec:
sourceModelUri: "hf://meta-llama/Llama-2-7b-hf"
nodeGroups:
- gpu-group
persistentVolumeClaim: llama-model-pvc
Lab 8: Debug a Distributed Training Deadlock
bash
# Create a job requiring more GPUs than available
cat <<'EOF' | kubectl apply -f -
apiVersion: batch.volcano.sh/v1alpha1
kind: Job
metadata:
name: deadlock-job
spec:
minAvailable: 100
schedulerName: volcano
tasks:
- replicas: 100
name: worker
template:
spec:
containers:
- name: worker
image: busybox
command: ["sh", "-c", "sleep 3600"]
resources:
limits:
nvidia.com/gpu: 1
EOF
sleep 10
# Debug
kubectl get pods -l volcano.sh/job-name=deadlock-job
kubectl describe podgroup deadlock-job
kubectl get events --field-selector involvedObject.name=deadlock-job
# Cleanup
kubectl delete job deadlock-job --ignore-not-found
Lab 9: End-to-End AI Inference Platform
bash
kubectl create namespace ai-platform
# Deploy vLLM
cat <<'EOF' | kubectl apply -n ai-platform -f -
apiVersion: apps/v1
kind: Deployment
metadata:
name: vllm
spec:
replicas: 2
selector:
matchLabels:
app: vllm
template:
metadata:
labels:
app: vllm
spec:
containers:
- name: vllm
image: vllm/vllm-openai:latest
args: ["--model", "facebook/opt-125m", "--enable-prefix-caching"]
resources:
limits:
nvidia.com/gpu: 1
ports:
- containerPort: 8000
---
apiVersion: v1
kind: Service
metadata:
name: vllm
spec:
selector:
app: vllm
ports:
- port: 8000
EOF
# KEDA
cat <<'EOF' | kubectl apply -n ai-platform -f -
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: vllm-scaler
spec:
scaleTargetRef:
name: vllm
minReplicaCount: 1
maxReplicaCount: 10
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus:9090
metricName: num_requests_waiting
threshold: "5"
query: sum(vllm:num_requests_waiting)
EOF
# Verify
kubectl get all -n ai-platform
kubectl get scaledobject -n ai-platform
# Cleanup
kubectl delete namespace ai-platform
PART 7: INCIDENT MANAGEMENT
31. AI Workload Incident Post-Mortem Template
text
INCIDENT: Distributed Training Deadlock - 16 GPUs Wasted
DATE: 2026-01-15
DURATION: 4 hours
SEVERITY: SEV-1
IMPACT: 16 GPUs held by blocked workers. No training progress.
TIMELINE:
14:00 - Job submitted: 16 workers, each needing 1 GPU
14:01 - 4 workers scheduled, 12 Pending
14:05 - 4 running workers hold 4 GPUs
14:10 - Deadlock detected (12 workers can't schedule)
14:15 - On-call acknowledged
14:30 - Identified missing gang scheduling
14:45 - Killed job, resubmitted with Volcano
15:00 - All 16 workers scheduled
18:00 - Training completed
ROOT CAUSE:
Job used default scheduler. No gang scheduling configured.
Partial placement held GPUs while waiting for peers.
LESSONS LEARNED:
1. All distributed training requires gang scheduling.
2. Partial placement is worse than no placement.
3. Volcano/KAI should be default for AI workloads.
ACTION ITEMS:
[ ] Enable Volcano for all AI namespaces (Owner: Platform)
[ ] Update job templates to use gang scheduling (Owner: ML Team)
[ ] Add deadlock detection alerts (Owner: SRE)
32. On-Call Runbook: AI Workload Failures
text
SYMPTOM: AI workload not progressing.
STEP 1: Check job status
$ kubectl get pods -l job-name=<job>
STEP 2: Check gang scheduling
$ kubectl get podgroup <name>
$ kubectl describe podgroup <name>
STEP 3: Check GPU availability
$ kubectl describe nodes | grep -A5 nvidia.com/gpu
STEP 4: Check queue status
$ kubectl get queue
STEP 5: Check inference engine
$ kubectl logs <vllm-pod> --tail=100
STEP 6: Check KV-cache
$ curl localhost:8000/metrics | grep prefix_cache
STEP 7: Check autoscaling
$ kubectl get hpa
$ kubectl describe scaledobject
STEP 8: Escalate
33. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | All training deadlocked / inference down | 5 min | On-call + Platform + ML Team |
| SEV-2 | Partial GPU waste / slow inference | 15 min | On-call + Platform |
| SEV-3 | Cold start slow / cache miss | 1 hour | On-call |
| SEV-4 | Cost anomaly | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
34. Junior-Level Questions
| Question | Expected Answer |
| Why does default Kubernetes fail at AI? | No gang scheduling, no topology awareness |
| What is gang scheduling? | All-or-nothing pod placement |
| What is vLLM? | High-throughput LLM inference engine |
| What is PagedAttention? | Memory-efficient KV-cache management |
| What is continuous batching? | Dynamic request batching |
35. Mid-Level Questions
| Question | Expected Answer |
| Kueue vs Volcano? | Kueue = admission; Volcano = full scheduler |
| What is a PodGroup? | Group of pods scheduled together |
| How do you autoscale vLLM? | KEDA with queue-depth metrics |
| What is KV-cache offloading? | Tiered storage for KV-cache |
| What is model caching? | Local NVMe caching for fast cold start |
36. Senior-Level Questions
| Question | Expected Answer |
| How do you prevent training deadlocks? | Gang scheduling with Volcano/KAI |
| How do you optimize cost per token? | vLLM + continuous batching + KV-cache |
| What is cache-aware routing? | Route requests to pods with warm cache |
| How do you handle cold starts? | Model caching + warm pools |
| What is llm-d? | Kubernetes-native distributed LLM inference |
37. Staff/Principal Questions
| Question | Expected Answer |
| Design an end-to-end AI platform. | Kueue + Volcano + vLLM + KEDA + model caching + llm-d |
| How do you get 73% cost reduction? | vLLM migration (Stripe case study) |
| How do you scale AI inference to 1M RPS? | Multi-region, cache-aware routing, warm pools |
| How do you handle multi-tenant GPU sharing? | Kueue queues + KAI Scheduler + MIG |
| How do you migrate from default scheduler to KAI? | Gradual, namespace by namespace |
Summary Cheat Sheet
| Concept | Key Takeaway |
| Default K8s | Individual pod placement, no gang scheduling |
| Gang Scheduling | All-or-nothing pod placement |
| PodGroup | Group of pods scheduled together |
| Kueue | Job admission, quota, fair sharing |
| ClusterQueue | Quota pool for Kueue |
| Volcano | Batch scheduling, gang, queue |
| KAI Scheduler | AI-aware, GPU sharing, topology |
| vLLM | PagedAttention, continuous batching |
| TGI | Hugging Face inference server |
| Triton | Multi-framework inference server |
| PagedAttention | Per-token-block KV-cache |
| Continuous Batching | Dynamic request batching |
| KV-Cache | Invisible state, 10x on hit |
| LMCache | KV-cache offloading to CPU/SSD |
| KEDA | Event-driven autoscaling |
| Model Caching | Local NVMe for fast cold start |
| Warm Pools | Pre-loaded model instances |
| llm-d | Cache-aware routing |
| Gateway API Inference | AI-aware routing extension |
Stage 14: Multi-Cluster & Platform Engineering — The Comprehensive Guide
PART 1: CORE THEORY
1. The Multi-Cluster Imperative
Single clusters don't scale indefinitely. Organizations adopt multi-cluster architectures for isolation, resilience, cost optimization, and regulatory compliance. But multi-cluster introduces complexity that single clusters never had.
Why Organizations Go Multi-Cluster
| Driver | Description |
| Isolation | Separate prod/staging/dev, separate teams, separate customers |
| Resilience | Survive zone, region, or provider failures |
| Compliance | Data residency (EU data stays in EU) |
| Scale | Beyond 1,000–5,000 nodes per cluster |
| Cost | Optimize by region or provider |
| Acquisition | Integrating acquired companies with their clusters |
The Hidden Costs
| Cost | Description |
| Operational overhead | N clusters × (upgrades + monitoring + backup + cert rotation) |
| Observability fragmentation | Metrics, logs, traces scattered |
| Policy drift | Clusters configured differently |
| Networking complexity | Cross-cluster service discovery |
| Security surface | More control planes to secure |
| Cost tracking | Harder to allocate spend |
The Platform Engineering Response
Platform Engineering is the discipline of building internal developer platforms (IDPs) that make multi-cluster Kubernetes manageable. It treats the platform as a product, with developers as customers.
| Traditional Ops | Platform Engineering |
| Tickets for infrastructure | Self-service |
| Manual provisioning | Golden paths |
| Per-team tooling | Standardized platform |
| Reactive | Proactive |
2. The Ownership Levels Framework
Multi-cluster and multi-tenancy decisions can be organized into four ownership levels. Understanding where you sit determines which tools to use.
The Four Levels
| Level | What You Own | Tools |
| Level 1: Multi-Cluster | Cluster lifecycle, provisioning | Cluster API, Terraform |
| Level 2: Multi-Tenancy | Tenant isolation within a cluster | vCluster, Capsule, namespaces |
| Level 3: Platform Engineering | Developer experience, self-service | Backstage, Crossplane |
| Level 4: Governance | Policy, compliance, cost | Kyverno, OPA, Kubecost |
Why the Framework Matters
Each level has distinct concerns and distinct tools. Confusing them leads to over-engineering (using vCluster when namespaces would suffice) or under-engineering (using namespaces when hard isolation is required).
3. vCluster
vCluster creates virtual Kubernetes clusters inside a host cluster. Each vCluster has its own API server, controller manager, and optional scheduler, but shares the host's worker nodes.
How vCluster Works
text
┌─────────────────────────────────────────────────────────────┐
│ HOST CLUSTER │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ vCluster A (Namespace: vcluster-a) │ │
│ │ • Virtual API server (synced to host) │ │
│ │ • Virtual controller manager │ │
│ │ • Virtual scheduler │ │
│ │ • Pods run as host pods │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ vCluster B (Namespace: vcluster-b) │ │
│ │ • Virtual API server │ │
│ │ • Virtual controller manager │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Both share the same host worker nodes. │
└─────────────────────────────────────────────────────────────┘
When to Use vCluster
| Scenario | vCluster? |
| Development environments | ✅ Yes |
| CI/CD pipelines | ✅ Yes |
| Multi-team SaaS platforms | ✅ Yes |
| Strong tenant isolation | ✅ Yes |
| Simple team isolation | ❌ Use namespaces |
| Production multi-region | ❌ Use separate clusters |
vCluster Benefits
| Benefit | Description |
| Fast | Create virtual clusters in seconds |
| Cheap | No additional nodes |
| Isolated | Each vCluster has own API server |
| Self-service | Developers manage their own cluster |
| Version-skew | Different vCluster versions on same host |
vCluster Limitations
| Limitation | Impact |
| No node isolation | Pods run on shared nodes |
| CRD conflicts | Same CRDs can't be installed twice |
| Host cluster dependency | vCluster fails if host fails |
| Networking | Cross-vCluster requires configuration |
4. Capsule
Capsule implements Namespace-as-a-Service multi-tenancy. It allows multiple tenants to share a single cluster without giving them cluster-level access.
How Capsule Works
Capsule introduces two CRDs:
| CRD | Purpose |
| Tenant | A tenant with assigned users, groups, and namespaces |
| TenantResourceQuota | Quota for a tenant |
Capsule Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ SHARED CLUSTER │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Tenant A (team-a) │ │
│ │ • Users: alice, bob │ │
│ │ • Namespaces: team-a-dev, team-a-prod │ │
│ │ • Quota: 100 CPU, 200 GiB memory │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Tenant B (team-b) │ │
│ │ • Users: charlie │ │
│ │ • Namespaces: team-b-dev │ │
│ │ • Quota: 50 CPU, 100 GiB memory │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
When to Use Capsule
| Scenario | Capsule? |
| Multi-team cluster | ✅ Yes |
| Namespace self-service | ✅ Yes |
| Quota per tenant | ✅ Yes |
| Hard isolation | ❌ Use vCluster |
| Single team | ❌ Use namespaces |
5. Cluster API
Cluster API (CAPI) is a Kubernetes sub-project that lets you manage the lifecycle of Kubernetes clusters using Kubernetes itself.
CAPI Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ MANAGEMENT CLUSTER │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ CAPI Core Controllers │ │
│ │ • Cluster, Machine, MachineSet │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ┌──────────────────────▼──────────────────────────────┐ │
│ │ Infrastructure Provider │ │
│ │ • AWSCluster, VSphereCluster │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ┌──────────────────────▼──────────────────────────────┐ │
│ │ Bootstrap Provider │ │
│ │ • KubeadmConfig │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ┌──────────────────────▼──────────────────────────────┐ │
│ │ Control Plane Provider │ │
│ │ • KubeadmControlPlane │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
CAPI Resources
| Resource | Purpose |
| Cluster | Defines a cluster |
| Machine | Represents a node |
| MachineSet | Group of machines |
| MachineDeployment | Declarative machine management |
| KubeadmControlPlane | Control plane management |
When to Use CAPI
| Scenario | CAPI? |
| Multi-cloud fleet | ✅ Yes |
| On-prem + cloud | ✅ Yes |
| Standardized provisioning | ✅ Yes |
| Single managed cluster | ❌ Use managed service |
6. Karmada
Karmada (Kubernetes Armada) is a CNCF-graduated project for multi-cluster, multi-cloud Kubernetes orchestration.
Karmada Architecture
| Component | Purpose |
| Karmada Control Plane | Central API, scheduler, controllers |
| Member Clusters | Workload clusters (push or pull mode) |
| ResourceBinding | Workload distribution decisions |
| PropagationPolicy | Where workloads should run |
Karmada Use Cases
| Use Case | Description |
| Hybrid cloud | Run workloads across AWS, GCP, on-prem |
| Multi-region | Distribute workloads globally |
| AI/ML training | Schedule across GPU clusters |
| Disaster recovery | Active-active multi-cluster |
Karmada v1.19 (2026)
The v1.19 release advances multi-component scheduling for distributed AI training jobs and promotes priority-based scheduling to Beta, enabled by default.
PART 2: ADVANCED CONCEPTS
7. Fleet
Fleet is Rancher's GitOps-driven multi-cluster management tool. It deploys applications across clusters using Git as the source of truth.
Fleet Architecture
| Component | Purpose |
| Fleet Manager | Central controller in management cluster |
| Fleet Agent | Runs in each managed cluster |
| GitRepo | Git repository to sync |
| Bundle | Set of resources to deploy |
Fleet vs Argo CD vs Flux
| Aspect | Fleet | Argo CD | Flux |
| Multi-cluster | ✅ Native | ✅ | ✅ |
| GitOps | ✅ | ✅ | ✅ |
| Rancher integration | ✅ | ❌ | ❌ |
| UI | Rancher | Argo UI | Weave GitOps |
8. Crossplane
Crossplane extends Kubernetes to manage cloud resources as CRDs. Instead of Terraform, you define cloud resources as Kubernetes objects.
Crossplane Architecture
| Component | Purpose |
| Provider | Cloud provider integration (AWS, GCP, Azure) |
| CompositeResource | Custom resource combining multiple cloud resources |
| Composition | Template for composite resources |
| Claim | Developer-facing request |
Crossplane Example
yaml
apiVersion: rds.aws.upbound.io/v1beta1
kind: Instance
metadata:
name: production-db
spec:
forProvider:
region: us-east-1
instanceClass: db.t3.medium
engine: postgres
allocatedStorage: 100
Crossplane vs Terraform
| Aspect | Crossplane | Terraform |
| Model | Kubernetes-native | CLI-driven |
| State | In Kubernetes | In state file |
| Drift detection | Continuous | On plan |
| Self-service | ✅ | ❌ |
| Multi-cloud | ✅ | ✅ |
9. Backstage
Backstage is an open-source Internal Developer Portal (IDP) created by Spotify. It provides a single pane of glass for developers to discover services, documentation, and tools.
Backstage Core Features
| Feature | Purpose |
| Software Catalog | All services, ownership, metadata |
| Software Templates | Golden paths for new services |
| TechDocs | Documentation as code |
| Plugins | Extensible ecosystem |
Backstage Plugins (2026)
| Plugin | Purpose |
| Kubernetes | View cluster resources |
| Argo CD | View deployments |
| Crossplane | Manage cloud resources |
| Kubecost | View costs |
10. Multi-Cluster GitOps
Argo CD Multi-Cluster
Argo CD manages multiple clusters from a single control plane.
yaml
apiVersion: v1
kind: Secret
metadata:
name: production-cluster
namespace: argocd
labels:
argocd.argoproj.io/secret-type: cluster
stringData:
name: production
server: https://production.example.com:6443
config: |
{
"tlsClientConfig": {
"insecure": false,
"caData": "..."
}
}
Flux Multi-Cluster
Flux uses cluster API and kustomization to sync across clusters.
GitOps Best Practices
| Practice | Why |
| One repo per cluster | Isolation |
| Separate config repos | Team autonomy |
| Use overlays | Environment-specific config |
| Automated drift detection | Detect unauthorized changes |
11. Multi-Cluster Service Discovery
Submariner
Submariner connects clusters across clouds and on-premises with cross-cluster L3 connectivity.
Cilium Cluster Mesh
Cilium Cluster Mesh connects multiple Kubernetes clusters with:
- Cross-cluster service discovery
- Global load balancing
- Unified network policy
Comparison
| Tool | Approach | CNCF Status |
| Submariner | L3 tunnels | Sandbox |
| Cilium Cluster Mesh | eBPF | Graduated |
| Karmada | Service propagation | Graduated |
12. Multi-Cluster Observability
Thanos
Thanos provides global query view over multiple Prometheus instances.
Grafana Mimir
Mimir is a scalable long-term storage for Prometheus metrics.
Grafana Loki
Loki provides multi-cluster log aggregation.
Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ MULTI-CLUSTER OBSERVABILITY │
│ │
│ Cluster A Cluster B Cluster C │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │Prometheus│ │Prometheus│ │Prometheus│ │
│ └────┬────┘ └────┬────┘ └────┬────┘ │
│ │ │ │ │
│ └──────────────┴──────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────┐ │
│ │ Thanos/Mimir │ │
│ │ (Global View)│ │
│ └───────┬───────┘ │
│ │ │
│ ▼ │
│ ┌───────────────┐ │
│ │ Grafana │ │
│ └───────────────┘ │
└─────────────────────────────────────────────────────────────┘
13. Multi-Cluster Policy
Kyverno Multi-Cluster
Kyverno can be deployed to multiple clusters and policies synced via GitOps.
OPA Gatekeeper Multi-Cluster
OPA Gatekeeper policies can be managed centrally and distributed.
Policy Distribution
| Tool | Approach |
| GitOps | Argo CD/Flux syncs policies |
| Karmada | PropagationPolicy |
| Fleet | GitRepo |
14. Cluster API v1.12
Cluster API v1.12 (January 2026) introduces two major features:
In-Place Updates
Previously, CAPI performed updates by deleting and recreating machines. In-place updates allow users to make changes on existing machines without delete-and-recreate.
Chained Upgrades
Chained upgrades allow clusters using managed topologies to upgrade by more than one minor Kubernetes version through efficient sequential upgrades.
Why This Matters
| Feature | Impact |
| In-place updates | Faster, less disruptive |
| Chained upgrades | Catch up multiple versions in one operation |
PART 3: PRODUCTION FAILURE MODES
15. Top 10 Multi-Cluster & Platform Failures
| # | Failure | Symptom | Root Cause | Fix |
| 1 | vCluster stuck | Virtual cluster unresponsive | Host cluster resource exhaustion | Check host resources |
| 2 | Karmada propagation failure | Workload not deployed | PropagationPolicy misconfigured | Check policy |
| 3 | CAPI reconciliation loop | Cluster stuck | Provider bug | Check CAPI logs |
| 4 | Crossplane resource conflict | Cloud resource not created | IAM permissions | Check provider logs |
| 5 | GitOps drift | Cluster differs from Git | Manual changes | Reconcile |
| 6 | Multi-cluster observability gap | Missing metrics | Prometheus scrape failure | Check ServiceMonitor |
| 7 | Policy drift across clusters | Inconsistent enforcement | Manual configuration | Central policy management |
| 8 | Backstage catalog stale | Wrong service info | Not synced | Check Backstage logs |
| 9 | Cluster API upgrade failure | Upgrade stuck | Version skew | Check CAPI logs |
| 10 | Cost allocation failure | Can't attribute costs | Missing labels | Enforce labels |
16. Multi-Cluster Debugging Runbook
"vCluster is Broken" — Step-by-Step
text
STEP 1: Check vCluster status
$ kubectl get vcluster -A
STEP 2: Check vCluster pods
$ kubectl get pods -n <vcluster-namespace>
STEP 3: Check vCluster logs
$ kubectl logs -n <vcluster-namespace> <vcluster-pod>
STEP 4: Check host cluster
$ kubectl get nodes
STEP 5: Check resource usage
$ kubectl top nodes
STEP 6: Escalate
"Karmada Workload Not Deployed" — Step-by-Step
text
STEP 1: Check Karmada control plane
$ kubectl get pods -n karmada-system
STEP 2: Check PropagationPolicy
$ kubectl get propagationpolicy -A
STEP 3: Check ResourceBinding
$ kubectl get resourcebinding -A
STEP 4: Check member clusters
$ kubectl get clusters
STEP 5: Check scheduler logs
$ kubectl logs -n karmada-system -l app=karmada-scheduler
STEP 6: Escalate
17. Blast Radius Analysis
What Happens When Multi-Cluster Fails?
| Component | Impact | Severity |
| Management cluster down | Can't manage fleet | SEV-1 |
| Karmada down | No cross-cluster scheduling | SEV-2 |
| CAPI down | No cluster provisioning | SEV-2 |
| GitOps down | No deployments | SEV-2 |
| Observability down | No visibility | SEV-2 |
| Single cluster down | Depends on multi-cluster setup | SEV-1 to SEV-3 |
PART 4: CAPACITY PLANNING & COST MODELING
18. Multi-Cluster Cost Modeling
Cost Components
| Component | Cost |
| Control plane | $70–$150/month per cluster (managed) |
| Worker nodes | $0.10–$3/hour per node |
| Networking | Cross-cluster data transfer |
| Observability | Storage for metrics/logs |
| Backup | S3/GCS storage |
The Multi-Cluster Cost Trap
| Trap | Impact |
| Idle clusters | Dev clusters running 24/7 |
| Duplicate observability | N Prometheus instances |
| No shared services | Each cluster has own logging, monitoring |
19. Platform Team Sizing and ROI
Platform Team Size by Organization
| Org Size | Platform Engineers |
| 50 developers | 2–4 |
| 200 developers | 5–10 |
| 1,000 developers | 20–40 |
Platform ROI
| Metric | Improvement |
| Developer onboarding | 2 weeks → 2 days |
| Deployment frequency | 10x |
| Change failure rate | 50% reduction |
| Mean time to recovery | 70% reduction |
20. SLA & Availability Design
Availability Math
text
99.9% = 8.76 hours downtime/year
99.99% = 52.56 minutes downtime/year
99.999% = 5.26 minutes downtime/year
Multi-Cluster SLA Design
| Target | Architecture |
| 99.9% | Single cluster, basic monitoring |
| 99.99% | Active-passive multi-cluster |
| 99.999% | Active-active multi-cluster, chaos-tested |
PART 5: ARCHITECTURE & STRATEGY
21. Internal Developer Platform Architecture
text
┌─────────────────────────────────────────────────────────────┐
│ IDP ARCHITECTURE │
│ │
│ Layer 1: Developer Portal │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Backstage — Catalog, Templates, Docs │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 2: Self-Service │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Crossplane — Cloud resources as CRDs │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 3: Multi-Cluster Management │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Cluster API, Karmada, Fleet │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 4: Multi-Tenancy │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ vCluster, Capsule │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 5: GitOps │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Argo CD, Flux │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Layer 6: Observability │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Thanos, Mimir, Loki │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
22. Platform Governance and Self-Service
Golden Paths
Golden paths are pre-approved templates that make the right way the easy way.
| Golden Path | Tool |
| New service | Backstage template |
| New database | Crossplane claim |
| New environment | vCluster |
| New cluster | Cluster API |
Self-Service Guardrails
| Guardrail | Tool |
| Resource quotas | ResourceQuota |
| Policy enforcement | Kyverno/OPA |
| Image signing | cosign + Kyverno |
| Network isolation | NetworkPolicy |
23. Compliance & Security for Multi-Cluster
| Framework | Multi-Cluster Requirement |
| PCI-DSS | Isolated clusters, audit logs |
| HIPAA | Audit trails, encryption |
| SOC2 | Change management, monitoring |
| GDPR | Data residency |
| FedRAMP | FIPS 140-2, STIG |
PART 6: HANDS-ON LABS
Lab 1: Deploy vCluster on Kubernetes
bash
# Install vCluster CLI
curl -L -o vcluster https://github.com/loft-sh/vcluster/releases/latest/download/vcluster-linux-amd64
chmod +x vcluster
sudo mv vcluster /usr/local/bin/
# Create a vCluster
vcluster create my-vcluster
# Connect to it
vcluster connect my-vcluster
# You now have a virtual cluster
kubectl get namespaces
kubectl get nodes
# Disconnect
vcluster disconnect
# Cleanup
vcluster delete my-vcluster
Lab 2: Multi-Tenancy with Capsule
bash
# Install Capsule
helm repo add projectcapsule https://projectcapsule.github.io/charts
helm install capsule projectcapsule/capsule -n capsule-system --create-namespace
# Create a Tenant
cat <<'EOF' | kubectl apply -f -
apiVersion: capsule.clastix.io/v1beta2
kind: Tenant
metadata:
name: team-a
spec:
owners:
- name: alice
kind: User
namespaceOptions:
quota: 5
resourceQuotas:
items:
- hard:
requests.cpu: "100"
requests.memory: 200Gi
limits.cpu: "200"
limits.memory: 400Gi
EOF
# Verify
kubectl get tenants
kubectl get namespaces -l capsule.clastix.io/tenant=team-a
Lab 3: Provision a Cluster with Cluster API
bash
# Install clusterctl
curl -L https://github.com/kubernetes-sigs/cluster-api/releases/download/v1.12.0/clusterctl-linux-amd64 -o clusterctl
chmod +x clusterctl
sudo mv clusterctl /usr/local/bin/
# Initialize management cluster
clusterctl init --infrastructure aws
# Generate cluster config
clusterctl generate cluster production \
--kubernetes-version v1.36.0 \
--control-plane-machine-count 3 \
--worker-machine-count 3 \
> production.yaml
# Apply
kubectl apply -f production.yaml
# Check status
clusterctl describe cluster production
kubectl get clusters
kubectl get machines
Lab 4: Deploy Karmada and Propagate Workloads
bash
# Install Karmada
helm repo add karmada https://raw.githubusercontent.com/karmada-io/karmada/master/charts
helm install karmada karmada/karmada -n karmada-system --create-namespace
# Join member clusters
karmadactl join member1 --cluster-kubeconfig=/path/to/member1
karmadactl join member2 --cluster-kubeconfig=/path/to/member2
# Create PropagationPolicy
cat <<'EOF' | kubectl apply -f -
apiVersion: policy.karmada.io/v1alpha1
kind: PropagationPolicy
metadata:
name: nginx-propagation
spec:
resourceSelectors:
- apiVersion: apps/v1
kind: Deployment
name: nginx
placement:
clusterAffinity:
clusterNames:
- member1
- member2
replicaScheduling:
replicaDivisionPreference: Weighted
replicaSchedulingType: Divided
weightPreference:
staticWeightList:
- targetCluster:
clusterNames:
- member1
weight: 1
- targetCluster:
clusterNames:
- member2
weight: 1
EOF
# Deploy workload
kubectl create deployment nginx --image=nginx --replicas=6
# Check propagation
kubectl get resourcebinding nginx-deployment -o yaml
Lab 5: Crossplane for Cloud Resources
bash
# Install Crossplane
helm repo add crossplane-stable https://charts.crossplane.io/stable
helm install crossplane crossplane-stable/crossplane -n crossplane-system --create-namespace
# Install AWS provider
cat <<'EOF' | kubectl apply -f -
apiVersion: pkg.crossplane.io/v1
kind: Provider
metadata:
name: provider-aws
spec:
package: xpkg.upbound.io/upbound/provider-aws-s3:v1.0.0
EOF
# Create an S3 bucket
cat <<'EOF' | kubectl apply -f -
apiVersion: s3.aws.upbound.io/v1beta1
kind: Bucket
metadata:
name: my-crossplane-bucket
spec:
forProvider:
region: us-east-1
providerConfigRef:
name: default
EOF
# Check status
kubectl get bucket
kubectl describe bucket my-crossplane-bucket
Lab 6: Backstage Developer Portal
bash
# Create Backstage app
npx @backstage/create-app@latest
# Start Backstage
cd my-backstage-app
yarn dev
# Access at http://localhost:3000
# Add Kubernetes plugin
yarn add --cwd packages/app @backstage/plugin-kubernetes
Lab 7: Multi-Cluster GitOps with Argo CD
bash
# Install Argo CD
kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
# Add clusters
argocd cluster add production-context
argocd cluster add staging-context
# Create Application
cat <<'EOF' | kubectl apply -f -
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: my-app
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/myorg/myapp
targetRevision: HEAD
path: manifests
destination:
server: https://production.example.com:6443
namespace: default
syncPolicy:
automated:
prune: true
selfHeal: true
EOF
# Check status
argocd app list
argocd app get my-app
Lab 8: Multi-Cluster Observability
bash
# Install Thanos
helm repo add bitnami https://charts.bitnami.com/bitnami
helm install thanos bitnami/thanos -n thanos --create-namespace
# Configure Prometheus remote write to Thanos
# In each cluster's Prometheus:
remote_write:
- url: http://thanos-receive:19291/api/v1/receive
# Query global view
# Access Thanos Query UI at http://thanos-query:9090
Lab 9: End-to-End Platform Engineering
bash
# This lab combines all components:
# 1. Management cluster with Cluster API
# 2. vCluster for developer environments
# 3. Capsule for tenant management
# 4. Crossplane for cloud resources
# 5. Backstage for portal
# 6. Argo CD for GitOps
# Step 1: Set up management cluster
kind create cluster --name management
# Step 2: Install Cluster API
clusterctl init --infrastructure docker
# Step 3: Provision workload clusters
clusterctl generate cluster dev --flavor development > dev.yaml
kubectl apply -f dev.yaml
# Step 4: Install vCluster on workload cluster
vcluster create dev-vcluster --namespace dev
# Step 5: Install Capsule
helm install capsule projectcapsule/capsule -n capsule-system --create-namespace
# Step 6: Install Crossplane
helm install crossplane crossplane-stable/crossplane -n crossplane-system --create-namespace
# Step 7: Install Argo CD
kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
# Step 8: Connect everything
# - Backstage to Argo CD
# - Argo CD to all clusters
# - Crossplane to cloud provider
# Verify
kubectl get all -A
PART 7: INCIDENT MANAGEMENT
33. Multi-Cluster Incident Post-Mortem Template
text
INCIDENT: Karmada Propagation Failure - Workload Not Deployed
DATE: 2026-01-15
DURATION: 3 hours
SEVERITY: SEV-2
IMPACT: New workload not deployed to any member cluster.
TIMELINE:
14:00 - Deployment created in Karmada control plane
14:05 - PropagationPolicy applied
14:10 - Workload not appearing in member clusters
14:15 - On-call acknowledged
14:30 - Checked PropagationPolicy: missing clusterAffinity
14:45 - Fixed policy
15:00 - Workload propagated
17:00 - Incident closed
ROOT CAUSE:
PropagationPolicy had no clusterAffinity. Karmada didn't know which
clusters to deploy to.
LESSONS LEARNED:
1. All PropagationPolicies must have explicit clusterAffinity.
2. Karmada propagation must be monitored.
3. Policy templates should include clusterAffinity.
ACTION ITEMS:
[ ] Update policy templates (Owner: Platform)
[ ] Add propagation monitoring (Owner: SRE)
[ ] Test propagation in staging (Owner: Platform)
34. On-Call Runbook: Multi-Cluster Failures
text
SYMPTOM: Workload not deployed across clusters.
STEP 1: Check management cluster
$ kubectl get pods -n karmada-system
$ kubectl get clusters
STEP 2: Check PropagationPolicy
$ kubectl get propagationpolicy -A -o yaml
STEP 3: Check ResourceBinding
$ kubectl get resourcebinding -A
STEP 4: Check member cluster
$ kubectl --context member1 get deployments -A
STEP 5: Check GitOps
$ argocd app list
STEP 6: Escalate
35. Escalation Matrix
| Severity | Impact | Response Time | Escalation |
| SEV-1 | Management cluster down / all clusters affected | 5 min | On-call + Platform + Management |
| SEV-2 | Propagation failure / GitOps down | 15 min | On-call + Platform |
| SEV-3 | Single cluster issue | 1 hour | On-call |
| SEV-4 | Configuration warning | 4 hours | Ticket |
PART 8: INTERVIEW PREPARATION
36. Junior-Level Questions
| Question | Expected Answer |
| What is vCluster? | Virtual Kubernetes cluster inside a host cluster |
| What is Capsule? | Namespace-as-a-Service multi-tenancy |
| What is Cluster API? | Declarative cluster provisioning |
| What is Karmada? | Multi-cluster orchestration (CNCF Graduated) |
| What is Backstage? | Internal Developer Portal |
37. Mid-Level Questions
| Question | Expected Answer |
| vCluster vs Capsule? | vCluster = virtual clusters; Capsule = namespace tenancy |
| What is Crossplane? | Cloud resources as Kubernetes CRDs |
| What is Fleet? | Rancher's multi-cluster GitOps |
| What is Submariner? | Cross-cluster networking |
| What is Thanos? | Global query view over Prometheus |
38. Senior-Level Questions
| Question | Expected Answer |
| How do you choose between vCluster and namespaces? | Isolation level required |
| How do you manage 100 clusters? | Cluster API + GitOps + observability |
| What is the Ownership Levels framework? | Multi-cluster → Multi-tenancy → Platform → Governance |
| How do you enforce policy across clusters? | GitOps + Kyverno/OPA |
| What is CAPI v1.12? | In-place updates, chained upgrades |
39. Staff/Principal Questions
| Question | Expected Answer |
| Design an Internal Developer Platform. | Backstage + Crossplane + CAPI + vCluster + Argo CD |
| How do you build golden paths? | Backstage templates + Crossplane claims |
| How do you measure platform ROI? | Onboarding time, deployment frequency, MTTR |
| How do you migrate from single to multi-cluster? | Phased approach, start with dev/test |
| How do you handle multi-cluster compliance? | Central policy, GitOps, audit logging |
Summary Cheat Sheet
| Concept | Key Takeaway |
| vCluster | Virtual Kubernetes clusters, fast, cheap |
| Capsule | Namespace-as-a-Service multi-tenancy |
| Cluster API | Declarative cluster provisioning |
| Karmada | Multi-cluster orchestration (CNCF Graduated) |
| Fleet | Rancher's multi-cluster GitOps |
| Crossplane | Cloud resources as K8s CRDs |
| Backstage | Internal Developer Portal |
| Argo CD | Multi-cluster GitOps |
| Flux | Multi-cluster GitOps |
| Submariner | Cross-cluster networking |
| Cilium Cluster Mesh | eBPF multi-cluster |
| Thanos | Global Prometheus view |
| Mimir | Long-term metrics storage |
| Loki | Multi-cluster logging |
| Ownership Levels | Multi-cluster → Multi-tenancy → Platform → Governance |
| CAPI v1.12 | In-place updates, chained upgrades |
| Golden Paths | Pre-approved templates |
| IDP | Internal Developer Platform |
Pillar 3 Complete: The Full Curriculum
You've now completed Pillar 3: Deep Kubernetes, Platform Engineering & Extensibility, covering:
| Stage | Topic |
| 1 | Kubernetes Fundamentals (Day 0/1) |
| 2 | kubectl Mastery & Debugging |
| 3 | Control Plane Internals |
| 4 | Workloads & Lifecycle Deep Dive |
| 5 | Scheduling Deep Dive |
| 6 | RBAC, ServiceAccounts & Security |
| 7 | Kubernetes Networking Deep Dive |
| 8 | Storage Deep Dive |
| 9 | Cluster Extensibility (CRDs, Controllers, Operators) |
| 10 | Autoscaling & Cost Optimization |
| 11 | Cluster Lifecycle & Operations |
| 12 | GPU Orchestration & Multi-Tenancy |
| 13 | AI/ML Workload Orchestration |
| 14 | Multi-Cluster & Platform Engineering |