Navigable 1:1 copy of the Pillar 3 Google Doc. Code appears in code blocks; tables, lists and headings are kept as in the original. ← Back to Master Syllabus

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:

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:

The Kubernetes Guarantee

You tell Kubernetes:

Kubernetes handles:

When Kubernetes Is Overkill

ScenarioBetter Alternative
Single server, simple appDocker Compose
Static websiteNetlify, Vercel, S3+CloudFront
Simple scheduled jobsCron on a VM
Local developmentDocker Compose, Tilt
Serverless functionsLambda, 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

ComponentPurpose
kube-apiserverREST API, the front door to Kubernetes. All communication goes through it.
etcdDistributed key-value store. The single source of truth for cluster state.
kube-schedulerWatches for unscheduled Pods, assigns them to nodes.
kube-controller-managerRuns controller loops (Deployment, ReplicaSet, Node, etc.).
cloud-controller-managerIntegrates with cloud providers (AWS, GCP, Azure).

Worker Node Components

ComponentPurpose
kubeletAgent on each node. Watches for Pods assigned to its node, ensures containers are running.
kube-proxyManages networking (iptables/IPVS rules for Services).
Container RuntimeRuns containers (containerd, CRI-O). Docker is deprecated.
PodsThe 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:

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

PatternDescriptionUse Case
SidecarHelper container alongside mainLog shipper, proxy, watcher
AmbassadorProxy to external serviceDatabase proxy, API gateway
AdapterTransform outputMetrics exporter, log formatter
Init ContainersRun before main containersDB 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

PhaseMeaning
PendingPod accepted, waiting for scheduling or image pull
RunningAt least one container running
SucceededAll containers completed successfully
FailedAt least one container failed
UnknownState couldn't be determined

Container States

StateMeaning
WaitingNot started yet (pulling image, waiting for dependency)
RunningExecuting
TerminatedFinished or crashed

Common Waiting Reasons

ReasonMeaning
ContainerCreatingRuntime is setting up the container
CrashLoopBackOffContainer keeps crashing and restarting
ImagePullBackOffCan't pull the image
ErrImagePullImage pull error (usually auth)
CreateContainerConfigErrorInvalid config (missing ConfigMap/Secret)

Pod Restart Policy

PolicyBehavior
AlwaysRestart on any exit (default)
OnFailureRestart only on non-zero exit
NeverNever 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

ParameterMeaningDefault
maxSurgeHow many extra Pods during update25%
maxUnavailableHow many Pods can be unavailable25%

Zero-downtime formula:

text
replicas >= maxUnavailable + 1

For replicas: 3, maxUnavailable: 0, maxSurge: 1:

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:

  1. ✅ Readiness probes — Kubernetes knows when a Pod is ready
  2. ✅ maxUnavailable: 0 — Never drop below desired replicas
  3. ✅ Graceful shutdown — Pods handle SIGTERM, finish in-flight requests
  4. ✅ preStop hooks — Delay before SIGTERM
  5. ✅ PodDisruptionBudgets — Protect against voluntary disruptions
  6. ✅ 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?

ProblemService Solution
Pod IPs changeStable ClusterIP + DNS name
Need load balancingService distributes across Pods
Cross-pod communicationService discovery via DNS
External accessNodePort, LoadBalancer

The Four Service Types

TypeAccessibilityUse Case
ClusterIPInternal onlyDefault, service-to-service
NodePortVia node IP + portDevelopment, on-prem
LoadBalancerCloud LBProduction external access
ExternalNameDNS aliasExternal services

ClusterIP (Default)

yaml
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: ClusterIP
  selector:
    app: nginx
  ports:
  - port: 80
    targetPort: 8080
    protocol: TCP

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:

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

  1. Service selects Pods via labels
  2. Kubernetes creates Endpoints objects (list of Pod IPs)
  3. kube-proxy programs iptables/IPVS rules
  4. 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

ConsumptionAuto-updates?
Env vars❌ No (requires Pod restart)
Volumes✅ Yes (within ~60s)

ConfigMap Best Practices

PracticeWhy
Use volumes for dynamic configAuto-updates
Use env vars for static configSimpler, no file I/O
Version control ConfigMapsGitOps
Don't store secretsUse Secrets instead
One ConfigMap per appEasier management
Use Helm/Kustomize for templatingAvoid 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

AspectConfigMapSecret
Data encodingPlain textBase64
Encryption at restOptionalOptional (but commonly enabled)
Size limit1 MB1 MB
Use caseNon-sensitive configPasswords, tokens, keys
Mount behaviorSameSame

Important: Secrets are not encrypted by default. They're base64-encoded, which is trivially decodable. Real security requires:

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

TypePurpose
OpaqueGeneric (default)
kubernetes.io/service-account-tokenServiceAccount tokens
kubernetes.io/dockercfgDocker registry credentials (legacy)
kubernetes.io/dockerconfigjsonDocker registry credentials
kubernetes.io/basic-authBasic auth
kubernetes.io/ssh-authSSH credentials
kubernetes.io/tlsTLS certificate + key
bootstrap.kubernetes.io/tokenBootstrap 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:

...can read them.

Real Secret Management

ApproachDescription
Encryption at restConfigure etcd encryption for Secrets
External Secrets OperatorSync from Vault, AWS Secrets Manager, etc.
Sealed SecretsEncrypt secrets in Git
SOPSEncrypt secrets with cloud KMS
Vault Agent InjectorInject 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:

ControllerNotes
NGINX IngressMost popular, stable
TraefikModern, easy config
HAProxy IngressHigh performance
ContourEnvoy-based
Istio GatewayIf using Istio
AWS Load Balancer ControllerAWS-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

TypeBehavior
PrefixMatch by URL path prefix
ExactMatch exact path only
ImplementationSpecificDepends 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)

AnnotationPurpose
nginx.ingress.kubernetes.io/rewrite-targetRewrite URL path
nginx.ingress.kubernetes.io/ssl-redirectForce HTTPS
nginx.ingress.kubernetes.io/proxy-body-sizeMax upload size
nginx.ingress.kubernetes.io/rate-limitRate limiting
nginx.ingress.kubernetes.io/auth-typeBasic auth
cert-manager.io/cluster-issuerAuto TLS via cert-manager

The Ingress Evolution: Gateway API

The Gateway API is the successor to Ingress, addressing its limitations:

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 CaseBenefit
Multi-teamIsolate teams
Multi-environmentdev, staging, prod in one cluster
Resource quotasLimit total resources per team
RBACRestrict users to specific namespaces
Network policiesIsolate traffic by namespace

Built-in Namespaces

NamespacePurpose
defaultWhere resources go if you don't specify
kube-systemKubernetes components (kube-dns, kube-proxy)
kube-publicPublic data (rarely used)
kube-node-leaseNode 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

AspectIsolated?
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 HelmWith Helm
Copy-paste YAML for each environmentOne chart, many values files
Manual versioningChart versions + release history
Painful rollbackshelm rollback
No dependency managementCharts can depend on charts

Core Concepts

ConceptDescription
ChartA package (directory) of Kubernetes manifests + templates
ReleaseAn instance of a chart deployed to a cluster
ValuesConfiguration variables
RepositoryA 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

FunctionPurpose
includeInclude a template
tplRender a string as template
toYamlConvert to YAML
nindentIndent + newline
defaultDefault value
quoteWrap in quotes
requiredFail if missing
lookupQuery cluster

Helm Best Practices

PracticeWhy
Use helm create as a starting pointBest-practice scaffold
One chart per applicationReusable, testable
Version charts semantically1.0.0, 1.1.0, 2.0.0
Store charts in a repoArtifact Hub, OCI, ChartMuseum
Use .helmignoreDon't ship garbage
Test with helm template before installCatch errors early
Use --atomic for installsRollback on failure
Use Helm Secrets or SOPS for secretsDon't commit secrets
Lint with helm lintCatch issues in CI

Helm vs Kustomize

AspectHelmKustomize
TemplatingGo templatesOverlays (no templating)
PackagingChartsDirectories
Valuesvalues.yamlPatches
EcosystemHuge (Artifact Hub)Native in kubectl
ComplexityHigherLower
Best ForDistributing appsConfiguring 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:

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:

Labels vs Annotations

AspectLabelsAnnotations
Used in selectors✅ Yes❌ No
Size limit63 chars256 KB total
PurposeIdentify and selectStore arbitrary metadata
Indexed by K8s✅ Yes❌ No

Standard Label Conventions

LabelUse
app.kubernetes.io/nameApplication name
app.kubernetes.io/instanceUnique instance ID
app.kubernetes.io/versionApp version
app.kubernetes.io/componentComponent (e.g., web, db)
app.kubernetes.io/part-ofParent system
app.kubernetes.io/managed-byTool (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

AspectRequestsLimits
PurposeGuaranteed minimumEnforced maximum
SchedulingUsed to find nodesNot used
CPUGuaranteed shareThrottled if exceeded
MemoryGuaranteedOOMKilled if exceeded
QoSDetermines classDetermines class

The Four Cases

CaseQoS ClassBehavior
Requests == LimitsGuaranteedHighest priority, best isolation
Requests < LimitsBurstableCan burst, may be throttled/killed
No requests/limitsBestEffortLowest 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

ValueMeaning
11 full CPU core
500m0.5 core (500 millicores)
100m0.1 core
1m0.001 core

Memory Units

ValueMeaning
MiMebibyte (1024²)
GiGibibyte (1024³)
MMegabyte (1000²)
GGigabyte (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

RuleWhy
Always set requestsPredictable scheduling
Set limits for memoryPrevent OOM of other Pods
Consider removing CPU limitsCPU is compressible; throttling hurts
Set requests = limits for critical appsGuaranteed QoS
Start with profiling dataDon't guess
Use VPA to recommend valuesData-driven sizing
Monitor throttlingcontainer_cpu_cfs_throttled_seconds_total

QoS Classes in Detail

QoSConditionsPriorityWhen Node Pressure
Guaranteedrequests == limits (CPU and memory)HighestKilled last
Burstablerequests < limitsMediumKilled if using > requests
BestEffortNo requests/limitsLowestKilled first

Eviction Order

When a node is under memory pressure:

  1. BestEffort Pods evicted first
  2. Burstable Pods exceeding requests evicted next
  3. 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:

AspectDeploymentStatefulSet
Pod namenginx-abc123 (random)postgres-0, postgres-1 (ordered)
HostnameRandomStable
StorageShared or nonePer-Pod PVC
Startup orderParallelSequential (0 → 1 → 2)
Shutdown orderParallelReverse (2 → 1 → 0)
Headless ServiceOptionalRequired

Use cases:

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:

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:

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:

ParameterPurpose
completionsNumber of successful completions
parallelismMax concurrent Pods
backoffLimitRetries before failure
activeDeadlineSecondsTimeout

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:

PolicyBehavior
AllowMultiple Jobs can run concurrently
ForbidSkip if previous Job still running
ReplaceKill previous, start new

PART 3: PRODUCTION FAILURE MODES

15. Top 10 Kubernetes Failures

#FailureSymptomRoot CauseFix
1CrashLoopBackOffPod keeps restartingApp crashes on startkubectl logs, fix app
2ImagePullBackOffCan't pull imageWrong tag, auth, networkCheck image, imagePullSecrets
3OOMKilledExit code 137Memory limit exceededIncrease limit, fix leak
4Pending podPod never schedulesNo nodes with resourcesCheck events, add capacity
5Service has no endpointsCan't reach ServiceWrong labels/selectorFix labels
6CreateContainerConfigErrorContainer fails to startMissing ConfigMap/SecretCreate the missing resource
7Readiness probe failurePod not ReadyApp not respondingFix probe or app
8PVC pendingVolume never bindsNo matching PV/StorageClassCheck StorageClass
9Ingress not routing404/502Wrong service/portCheck Ingress config
10Node NotReadyNode unavailableKubelet down, disk fullSSH, 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

StatusLikely CauseCheck
CrashLoopBackOffApp errorkubectl logs --previous
ImagePullBackOffImage/authkubectl describe pod
PendingResources/affinitykubectl describe pod
OOMKilledMemory limitIncrease limit, check leaks
Readiness probe failedApp slowTune probe
Service no endpointsLabelskubectl get endpoints

17. Blast Radius Analysis

What Happens When Kubernetes Fails?

ComponentImpactSeverity
API server downCan't manage cluster; running Pods continueSEV-1
etcd downControl plane can't functionSEV-1
Scheduler downNew Pods stay PendingSEV-2
Controller Manager downNo reconciliationSEV-2
Node NotReadyPods evicted after timeoutSEV-1
CNI failurePods lose networkSEV-1
DNS failureService discovery breaksSEV-1
Ingress downExternal access failsSEV-1

Mitigation Strategies

StrategyImplementation
Multi-master control plane3+ masters, etcd quorum
Multiple replicasAt least 2-3 per workload
PodDisruptionBudgetsProtect during disruptions
Anti-affinitySpread replicas across nodes
Backup etcdRegular snapshots
GitOpsDeclarative, versioned
MonitoringPrometheus, alerts

PART 4: CAPACITY PLANNING & COST MODELING

18. Cluster Sizing Fundamentals

Node Sizing

Workload TypeNode SizeWhy
General apps4–8 vCPU, 16–32 GBBalanced
Databases8–16 vCPU, 64–128 GBMemory + I/O
ML trainingGPU nodesSpecialized hardware
BatchHigh CPUCompute-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:

19. Resource Overcommit and Cost Optimization

Overcommit Ratios

ResourceSafe OvercommitRisk
CPU2–4xThrottling
Memory1–1.5xOOMKill
Disk1xCapacity exhaustion

Cost Optimization Tactics

TacticSavings
Right-size requests/limits20–40%
Use Spot/Preemptible nodes60–80% for interruptible
Bin-packing20–30%
AutoscalingVariable
Reserved instances30–60%
Multi-tenancy30–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

TargetArchitecture
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


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

ModelIsolationBest For
NamespacesLogicalInternal teams
vClusterVirtual clustersStrong isolation on shared clusters
Separate clustersPhysicalExternal customers, compliance
CapsuleHierarchical namespacesEnterprise multi-tenancy

Recommendation:


23. Compliance & Security

FrameworkK8s Requirement
PCI-DSSNetwork segmentation, RBAC, audit logs
HIPAAEncryption, audit, access controls
SOC2Change management, monitoring
FedRAMPFIPS 140-2, hardened configs

CIS Kubernetes Benchmark key items:


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

SeverityImpactResponse TimeEscalation
SEV-1Complete outage / all pods down5 minOn-call + Platform + Management
SEV-2Partial outage / degraded performance15 minOn-call + Platform
SEV-3Single service issue1 hourOn-call
SEV-4Config drift / warning4 hoursTicket

PART 8: INTERVIEW PREPARATION

36. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
PodSmallest unit. Ephemeral. Multi-container via shared net/volume.
DeploymentManages ReplicaSets. Rolling updates. Rollback.
ServiceStable endpoint. 4 types: ClusterIP, NodePort, LoadBalancer, ExternalName.
ConfigMapNon-sensitive config. Env vars or volumes.
SecretSensitive config. Base64 (not encrypted by default).
IngressHTTP routing. Requires an Ingress Controller.
NamespaceLogical partition. Not a security boundary by default.
HelmPackage manager. Charts + values + releases.
Labels/SelectorsThe glue of K8s.
Requests/LimitsRequests for scheduling, limits for enforcement.
StatefulSetStable identity + per-Pod storage.
DaemonSetOne Pod per node.
Job/CronJobRun-to-completion, scheduled.
QoSGuaranteed / Burstable / BestEffort.
Zero-downtimemaxUnavailable: 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

FactDetail
LanguageGo
ProtocolREST (HTTP/HTTPS)
AuthenticationFrom kubeconfig (certs, tokens, exec plugins)
AuthorizationAPI server enforces RBAC
Config location~/.kube/config (default)
Env overridesKUBECONFIG, KUBECTL_CONTEXT, KUBECTL_NAMESPACE

What kubectl Is Not

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:

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

SectionPurpose
clustersAPI server URLs and CA certs
usersCredentials (certs, tokens, exec plugins)
contextsCombinations 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

MethodWhere Used
Client certificatesSelf-managed clusters
Bearer tokensServiceAccounts, CI
Exec pluginsAWS (aws eks get-token), GCP, Azure
OIDCEnterprise SSO
Basic authLegacy (deprecated)
WebhookCustom 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

PatternRisk
Sharing kubeconfig filesAuditing becomes impossible
Committing kubeconfig to GitLeaks credentials
Using admin context for daily workToo much privilege
Skipping context checkRunning 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:

LevelExampleUse Case
Pure imperativekubectl run nginx --image=nginxQuick tests, debugging
Imperative with outputkubectl create deployment web --image=nginx --dry-run=client -o yaml > web.yamlGenerating manifests
Declarative applykubectl apply -f web.yamlStandard workflow
GitOpsArgo CD / Flux watches GitProduction standard

The Best Practice

Use imperative for:

Use declarative for:

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

CommandWhat It Does
--dry-run=clientOnly validates client-side, doesn't send to server
--dry-run=serverSends to server, validates server-side (admission, etc.)
-o yamlOutputs as YAML
-o jsonOutputs 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

CommandPurpose
kubectl applyApply manifests
kubectl createCreate from imperative
kubectl editEdit live resource
kubectl patchPartial update
kubectl scaleScale replicas
kubectl set imageUpdate image
kubectl rolloutManage rollouts
kubectl port-forwardLocal port forward
kubectl cpCopy files
kubectl topResource usage
kubectl auth can-iCheck permissions
kubectl explainBuilt-in docs
kubectl api-resourcesAvailable resource types
kubectl api-versionsAvailable API versions
kubectl cluster-infoCluster endpoint info

5. kubectl apply vs create vs replace

This is where declarative Kubernetes gets subtle.

The Three Commands

CommandBehavior
kubectl createCreate resource; fail if exists
kubectl replaceReplace resource entirely; must exist
kubectl applyCreate or update; uses 3-way merge

The 3-Way Merge

kubectl apply compares three things:

  1. Last applied configuration (stored in kubectl.kubernetes.io/last-applied-configuration annotation)
  2. New configuration (what you're applying now)
  3. 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

ActionBehavior
Field in manifestManaged by apply
Field removed from manifestApply removes it (via 3-way merge)
Field added externallyPreserved unless you explicitly remove

Server-Side Apply (SSA)

The modern alternative:

bash
kubectl apply --server-side -f deployment.yaml

Key differences:

AspectClient-Side ApplyServer-Side Apply
Merge locationkubectlAPI server
State storagelast-applied-configuration annotationmanagedFields
Conflict handlingWhole-resourceField-level
Multiple controllersHardEasy
PerformanceSlower (client does work)Faster

Server-side apply is the future. Used by Flux, Argo CD, and most modern tooling.

When to Use Which

ScenarioCommand
Initial creation, one-offkubectl create
Complete replacementkubectl replace (rare)
Day-to-day declarativekubectl apply (client or server)
Multiple controllerskubectl apply --server-side
CI/CDkubectl 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

FormatFlagUse Case
TabledefaultHuman reading
Wide-o wideMore columns
YAML-o yamlFull resource, editable
JSON-o jsonMachine parsing
Name-o nameJust 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:

JSON

bash
kubectl get pod nginx-abc123 -o json
kubectl get pod nginx-abc123 -o json | jq '.status.containerStatuses'

Use for:

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:

PatternPurpose
.metadata.namePod name
.status.podIPPod IP
.spec.nodeNameNode name
.status.phasePod phase
.spec.containers[*].imageAll container images
.metadata.labelsAll 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:

ScenarioCustom Column
Capacity auditNAME:.metadata.name,CPU:.spec.containers[0].resources.requests.cpu,MEM:.spec.containers[0].resources.requests.memory
Image auditNAME:.metadata.name,IMAGE:.spec.containers[*].image
Node assignmentNAME:.metadata.name,NODE:.spec.nodeName
Missing limitsNAME:.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

NeedCommand
All Pod nameskubectl get pods -o name
Pod IPskubectl 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:

FieldPurpose
metadata.namePod name
metadata.namespaceNamespace
spec.nodeNameNode name
status.phasePending/Running/Succeeded/Failed
status.podIPPod 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

TypeFlagFormat
Strategic mergedefaultYAML fragment
JSON merge--type=mergeJSON fragment
JSON patch--type=jsonRFC 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

ScenarioPatch Type
Simple field changeStrategic merge
Array element updateStrategic merge
Add/remove specific fieldJSON patch
Conditional updateJSON patch with test
Atomic multi-field changeJSON patch

The kubectl patch Advantage

Patches are:

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

ReasonMeaning
ScheduledPod assigned to node
PullingPulling image
PulledImage pulled successfully
FailedImage pull failed
BackOffRetry backoff
CreatedContainer created
StartedContainer started
KillingContainer being killed
UnhealthyProbe failed
FailedSchedulingCan't schedule
EvictedPod evicted (node pressure)
FailedMountVolume mount failed
FailedAttachVolumeVolume attach failed

Event Retention

Events are ephemeral. By default, they last 1 hour in etcd. This means:

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 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:

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:

Example:

yaml
ephemeralContainers:
- name: debugger
  image: busybox
  command: ['sh']
  targetContainerName: nginx
  stdin: true
  tty: true

Common Debug Images

ImagePurpose
busyboxSmall, has basic tools
nicolaka/netshootNetwork debugging (tcpdump, dig, curl)
alpineSlightly larger, has more tools
ubuntuFull Linux environment
koolkits/kubernetesKubernetes-focused
koolkits/javaJava-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

RiskMitigation
Ephemeral container escapeRBAC restrict pods/ephemeralcontainers
Privileged debuggingAvoid --profile=sysadmin unless needed
Data exposureDebug containers can read Pod filesystem
PersistenceEphemeral 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:

Use cases:

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:

Alternatives for distroless:


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

PluginPurpose
kubectx (ctx)Switch contexts fast
kubens (ns)Switch namespaces fast
neatClean YAML output
treeResource hierarchy
who-canCheck permissions
outdatedFind outdated images
imagesList images per workload
resource-capacityCluster capacity view
tailMulti-Pod log tailing
view-secretDecode Secrets
costCost visibility
popeyeCluster sanitizer
kubectl-icePer-Pod resource view
kubectl-kruiseEnhanced rolling updates
kubectl-node-shellSSH 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)

ToolPurpose
k9sFull-screen TUI for Kubernetes
kubectl-aliasesShell aliases for common commands
kubieContext-aware kubeconfig manager
kubespyLive watch a resource type
sternMulti-Pod log tailing (better than kubectl tail)
popeyeCluster sanitizer
kubectl-neatClean 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

Server-side dry run:

bash
kubectl apply -f deployment.yaml --dry-run=server

Use cases:

ScenarioDry Run Mode
Generate manifest from imperative--dry-run=client -o yaml
Validate YAML syntax--dry-run=client
Check admission webhooks--dry-run=server
Preview changeskubectl 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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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

#FailureSymptomRoot CauseFix
1Debugging in wrong context"Why isn't this working?"Current context ≠ intended clusterkubectl config current-context
2Debugging in wrong namespace"Pod not found"Wrong namespacekubectl config view --minify
3Events expiredNo events to inspectEvents last 1 hourUse event exporter
4Logs goneCan't find root causeContainer restarted, old logs goneUse --previous or log aggregation
5Distroless no-shellCan't execImage has no shellUse kubectl debug
6Metrics API downkubectl top failsmetrics-server not installedInstall metrics-server
7Version skewCommand fails oddlykubectl too old/newMatch kubectl version
8RBAC denied"forbidden" errorsInsufficient permissionskubectl auth can-i
9Wrong resource name"not found"Typo, wrong kindkubectl get <resource>
10Stale kubeconfigAuth failuresToken expired, cert expiredRe-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

SymptomFirst CommandThen
Pod not startingkubectl describe podkubectl logs --previous
Service unreachablekubectl get endpointskubectl describe svc
Node issueskubectl describe nodeSSH to node
Permission deniedkubectl auth can-iCheck RBAC
Slow performancekubectl topCheck limits
"Not found"kubectl config current-contextVerify namespace

19. Blast Radius Analysis

When kubectl Fails

ComponentImpactSeverity
kubectl unavailableCan't manage clusterSEV-2
kubeconfig lostCan't authenticateSEV-2
API server downkubectl unusable; Pods keep runningSEV-1
RBAC revokedSpecific user blockedSEV-2
Wrong contextActions in wrong clusterSEV-1 (potential)

Mitigation

StrategyImplementation
Backup kubeconfigSecure storage
Multiple kubeconfigsPer-cluster, per-role
kubectx/kubensAvoid wrong-context mistakes
Shell promptShow current context
RBAC auditingRegular kubectl auth can-i reports
Emergency accessBreak-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

TargetApproach
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:

MethodDescription
Admin kubeconfigStored securely offline
Cloud IAM roleAWS/GCP/Azure admin role
Emergency service accountStatic token, secret-stored
Node SSHDirect node access as backup

PART 5: ARCHITECTURE & STRATEGY

23. Standardizing kubectl Across Teams

The Standard Tooling

ToolPurpose
kubectlCore CLI
kubectx/kubensContext/namespace switching
k9sTUI
sternMulti-Pod logs
krewPlugin manager
kubectl-neatClean YAML output
yqYAML 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

AspectImperative CIGitOps
Who applies?CI pipelineIn-cluster controller
Source of truthCI logsGit
Drift detectionManualAutomatic
RollbackRerun pipelineGit revert
Best forLegacyModern

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

PracticeWhy
Least privilegeMinimal permissions per role
No cluster-admin for humansUse break-glass only
Namespace-scopedPrefer Role over ClusterRole
Audit accessLog all API calls
Rotate credentialsShort-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:

Emergency process:

  1. Announce incident
  2. Retrieve break-glass credentials
  3. Fix the issue
  4. Rotate credentials
  5. 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

SeverityImpactResponse TimeEscalation
SEV-1Cluster-wide outage5 minOn-call + Platform + Management
SEV-2Service outage / degraded15 minOn-call + Platform
SEV-3Single Pod issue1 hourOn-call
SEV-4Configuration issue4 hoursTicket

PART 8: INTERVIEW PREPARATION

38. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
kubectlClient that talks to API server via REST
kubeconfigConfig file with clusters/users/contexts
Contextcluster + user + namespace
Imperativekubectl run, create, set, scale
Declarativekubectl apply
Apply 3-way mergelast-applied + new + live
Server-side applyBetter than client-side, used by GitOps
-o jsonpathExtract specific fields
-o custom-columnsCustom table output
-o yamlFull resource
kubectl describeHuman-readable + Events
EventsCluster notifications, last ~1 hour
kubectl debugEphemeral containers for distroless
kubectl patchModify specific fields
kubectl diffPreview changes
CrashLoopBackOffApp crashing → check logs --previous
ImagePullBackOffImage problem → check Events
PendingScheduling problem → check describe Events
OOMKilledMemory limit → increase or fix leak
No endpointsSelector 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

ComponentRoleStateful?
kube-apiserverREST API, the only component that talks to etcdStateless
etcdKey-value store, the single source of truthStateful
kube-schedulerAssigns Pods to NodesStateless
kube-controller-managerRuns reconciliation loopsStateless

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:

Step 2: Authorization (AuthZ)

The API server checks permissions using:

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:

  1. Mutating admission controllers run first. They can modify the object.
  2. 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

FactDetail
All cluster state lives in etcdPods, Services, ConfigMaps, Secrets, RBAC, everything
etcd uses Raft consensusGuarantees consistency across nodes
etcd must have quorumMajority of nodes must agree
etcd is the performance bottleneckSlow 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

RequirementRecommendation
DiskSSD or NVMe with low fsync latency
Disk latency< 10ms for fsync
NetworkLow latency between etcd nodes (< 10ms)
MemoryDefault 8 GB limit; monitor for quota issues
CPU2-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

ParameterDefaultRecommended (Cross-AZ)
heartbeat-interval100ms200ms
election-timeout1000ms1500ms+

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 PointPurpose
QueueSortOrder Pods in the scheduling queue
PreFilterPre-process Pod info
FilterEliminate unsuitable nodes
PostFilterHandle unschedulable Pods (preemption)
PreScorePre-process scoring
ScoreRank feasible nodes
ReserveReserve resources
PermitAllow/deny/wait
PreBindPre-binding setup
BindFinalize 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:

  1. Observes the current state
  2. Compares it to the desired state
  3. 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

ControllerWhat It Reconciles
DeploymentReplicaSets for Deployments
ReplicaSetPods for ReplicaSets
NodeNode lifecycle, evictions
JobPods for Jobs
CronJobJobs on schedule
ServiceAccountSA tokens
EndpointSliceService endpoints
NamespaceNamespace lifecycle
PersistentVolumePV/PVC binding

Special Roles

The controller-manager also:


PART 2: ADVANCED CONCEPTS

6. Admission Webhooks

Mutating vs Validating

AspectMutatingValidating
PurposeModify the objectAllow or deny
WhenFirst phaseSecond phase
Can modify?✅ Yes❌ No
Can deny?✅ Yes✅ Yes

The Ordering

  1. Mutating webhooks run first.
  2. Validating admission policies run.
  3. Validating webhooks run last.

Critical: Mutations by mutating webhooks cause all previously called webhooks to be called again.

Failure Policy

PolicyBehavior
FailReject the request if the webhook is unreachable
IgnoreAllow 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

ControllerPurpose
MutatingAdmissionWebhookExternal mutating webhooks
MutatingAdmissionPolicyDeclarative in-API mutations
ValidatingAdmissionWebhookExternal validating webhooks
ValidatingAdmissionPolicyDeclarative 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

ConceptPurpose
FlowSchemaCategorize incoming requests
PriorityLevelConfigurationAssign priority levels
QueueBuffer requests during bursts
Fair QueuingPrevent 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:

LevelPurpose
systemControl plane components
workload-highCritical workloads
workload-lowStandard workloads
global-defaultEverything else
catch-allFallback

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

ExtensionAPI Group
metrics-servermetrics.k8s.io
Custom Metricscustom.metrics.k8s.io
Service Catalogservicecatalog.k8s.io
KubeVirtkubevirt.io

When to Use Aggregation vs CRDs

ApproachUse When
CRDsYou need custom resources with standard API behavior
AggregationYou 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

StepAction
1All instances try to acquire a Lease object in kube-system
2The winner becomes leader and does the work
3The leader periodically renews the lease
4If 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

ParameterDefaultMeaning
leaseDuration15sHow long the lease is valid
renewDeadline10sLeader must renew before this
retryPeriod2sHow 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

ComponentRule
kube-apiserver (HA)Newest and oldest instances within one minor version
kubeletMust not be newer than apiserver; up to 3 minor versions older (2 for < 1.25)
kube-proxyMust not be newer than apiserver; up to 3 minor versions older
kubectlWithin one minor version of apiserver (older or newer)

Examples

ScenarioSupported?
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

CertificateDefault Validity
kube-apiserver serving cert1 year
kube-apiserver client cert1 year
etcd serving cert1 year
etcd peer cert1 year
kubelet client cert1 year
kubelet serving cert1 year
CA certificate10 years

Rotation Methods

MethodDescription
kubeadmkubeadm certs renew all
kuceroAutomatic daemonset-based rotation
ManualRegenerate and replace certificates
Cloud-managedManaged by provider (EKS, GKE, AKS)

Kucero is a Kubernetes daemonset that performs automatic control plane certificate rotation.

The Rotation Procedure

  1. Plan a maintenance window (control plane will be briefly unavailable)
  2. Back up etcd and certificates
  3. Run rotation command
  4. Restart control plane components
  5. 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

OperationWhat It Does
CompactionRemoves old revisions from the logical keyspace
DefragmentationReclaims 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

ComponentPurpose
ReflectorWatches API server for changes
DeltaFIFOQueue of changes
IndexerLocal cache for fast reads
WorkqueueRate-limited work queue for the controller

Why This Design


14. Cloud Controller Manager

cloud-controller-manager integrates Kubernetes with cloud providers.

What It Does

ControllerCloud Integration
NodeAdds cloud metadata to Nodes
RouteConfigures cloud network routes
ServiceProvisions cloud load balancers
VolumeProvisions 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

#FailureSymptomRoot CauseFix
1etcd quorum lostAPI server unresponsiveLost majority of etcd nodesRestore quorum from remaining nodes
2etcd disk fullAPI server errors, etcd alarmDatabase grew beyond quotaDefragment, increase quota
3etcd slow diskHigh API latencyHDD instead of SSDMove to SSD/NVMe
4Certificates expiredkubelet can't connectNo rotationRotate certificates
5Webhook blockingAll API writes failWebhook failurePolicy=Fail, webhook downPatch to Ignore temporarily
6Leader election flappingControllers not reconcilingNetwork latency, clock skewFix network, NTP
7API server overload429 errors, timeoutsToo many requestsEnable APF, increase replicas
8etcd leader election stormHigh etcd latencyNetwork latency > election-timeoutTune heartbeat/election
9Controller manager OOMControllers not runningMemory leakIncrease memory, investigate
10Version skew violationSubtle failuresComponents on incompatible versionsUpgrade 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?

ComponentImpactSeverity
etcd downCluster unrecoverable; all state lostSEV-1
API server downCan't manage cluster; Pods keep runningSEV-1
Scheduler downNew Pods stay PendingSEV-2
Controller manager downNo reconciliationSEV-2
One etcd node downNo impact (quorum maintained)SEV-3
Two etcd nodes down (3-node cluster)Quorum lost, cluster brokenSEV-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

StrategyImplementation
3-node etcdTolerates 1 failure
5-node etcdTolerates 2 failures
etcd backupRegular snapshots
Certificate rotationkubeadm or kucero
Webhook failurePolicyCareful with Fail vs Ignore
APFProtect against overload

PART 4: CAPACITY PLANNING & COST MODELING

18. etcd Sizing and Performance

etcd Capacity Planning

Cluster Sizeetcd NodesCPUMemoryDisk
< 100 nodes328 GB50 GB SSD
100-500 nodes3416 GB100 GB SSD
500-1000 nodes5832 GB200 GB NVMe
> 1000 nodes51664 GB500 GB NVMe

etcd Performance Metrics

MetricTarget
fsync latency< 10ms
WAL fsync duration< 25ms (p99)
DB size< 2 GB
Leader changes0 per hour (stable)
Request latency< 50ms (p99)

The Disk I/O Warning

Mechanical HDDs have fsync latency > 10ms. This causes:

Always use SSD or NVMe for etcd.


19. Control Plane Capacity Planning

API Server Scaling

FactorImpact
Requests/secondMore API server replicas
WebhooksEach webhook adds latency
APFProtects against overload
Load balancerRequired for HA

API Server Resource Requirements

Cluster SizeCPU per replicaMemory per replica
< 100 nodes24 GB
100-500 nodes48 GB
500-1000 nodes816 GB
> 1000 nodes1632 GB

Scheduler and Controller Manager

ComponentCPUMemory
Scheduler22 GB
Controller Manager24 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

TargetArchitecture
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

FailureFailover Time
API server podInstant (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

PrincipleWhy
Odd number of control planesMaintains quorum
Load balancer for API serverHigh availability
Separate etcd disksI/O isolation
Cross-AZ deploymentFault isolation
Consistent versionsAvoid skew

22. Multi-Cluster Control Plane Strategy

StrategyDescriptionBest For
Single clusterOne control plane, many workersSmall teams
Multi-clusterSeparate control planes per environmentProduction
Hub-and-spokeCentral control plane, remote workersEdge
Cluster APIDeclarative cluster managementFleet management

The Management Cluster Pattern

text
┌─────────────────────────────────────────────────────────────┐
│  Management Cluster                                         │
│  (Cluster API, Argo CD, Monitoring)                        │
│                                                             │
│    ┌───────────────┐  ┌───────────────┐                   │
│    │ Workload      │  │ Workload      │                   │
│    │ Cluster 1     │  │ Cluster 2     │                   │
│  └───────────────┘  └───────────────┘                   │
└─────────────────────────────────────────────────────────────┘

23. Compliance & Security

FrameworkControl Plane Requirement
PCI-DSSEncryption at rest (etcd), audit logs, RBAC
HIPAAEncryption, audit trails, access controls
SOC2Change management, monitoring
FedRAMPFIPS 140-2, hardened control plane

CIS Kubernetes Benchmark Key Items


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

SeverityImpactResponse TimeEscalation
SEV-1etcd down / quorum lost / API server down5 minOn-call + Platform + Management
SEV-2Scheduler down / controller manager down15 minOn-call + Platform
SEV-3Single etcd node down (quorum intact)1 hourOn-call
SEV-4Certificate expiring soon4 hoursTicket

PART 8: INTERVIEW PREPARATION

36. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
API ServerFront door. Only component that talks to etcd.
etcdSingle source of truth. Raft consensus. Needs quorum.
Quorumfloor(N/2) + 1. 3 nodes = 1 failure. 5 nodes = 2 failures.
Odd numbersEven doesn't improve fault tolerance.
SchedulerFilter → Score → Bind. One Pod, one node.
Controller ManagerReconciliation loops. Leader election in HA.
AdmissionMutating first, then Validating.
Webhook failurePolicyFail = reject if down. Ignore = allow if down.
APFPriority and fairness for API server overload.
Leader ElectionLease object in kube-system. ~15s failover.
Version Skew3 minor versions for kubelet, 1 for apiserver.
Cert Rotationkubeadm certs renew.
etcd CompactionRemoves old revisions.
etcd DefragReclaims disk space.
Aggregation LayerExtends 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

WorkloadStateless?Identity?Storage?Ordering?Use Case
Deployment✅❌Shared❌Web apps, APIs
StatefulSet❌✅Per-Pod✅Databases, queues
DaemonSet✅N/ANode-localN/AAgents, 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:


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

StrategyBehaviorDowntimeUse Case
RollingUpdateGradual replacement❌ NoneDefault, production
RecreateKill all, then create new⚠️ YesDev, 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:

maxSurgemaxUnavailableBehavior
10Surge by 1, never drop below desired
25%25%Balanced (default)
01No extra pods, one unavailable
11Fast 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-PatternWhy It's Bad
maxUnavailable: 100%All pods down during update
replicas: 1No HA; every update is downtime
No readiness probeTraffic routed to not-ready pods
revisionHistoryLimit: 0Can't rollback
:latest image tagNon-deterministic updates
No resource requests/limitsUnpredictable scheduling

3. StatefulSets

A StatefulSet manages stateful applications that require:

The Identity Guarantee

AspectDeploymentStatefulSet
Pod nameweb-abc123-xyz (random)web-0, web-1, web-2 (ordered)
HostnameSame as Pod nameSame as Pod name (stable)
DNSRandomweb-0.web.default.svc.cluster.local
StorageShared or nonePer-Pod PVC (persistent)
Startup orderParallelSequential (0 → 1 → 2)
Termination orderParallelReverse (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:

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

StrategyBehaviorDowntime
RollingUpdateUpdate Pods in reverse order❌ None (if HA)
OnDeleteManual Pod deletion triggers updateManual control
PartitionedUpdate only Pods ≥ partitionCanary 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

ApplicationWhy StatefulSet
PostgreSQL / MySQLNeeds stable storage per replica
MongoDB replica setsMembers need stable identities
Kafka / RabbitMQBrokers need stable IDs
ElasticsearchNodes need stable names
ZooKeeper / etcdConsensus requires stable IDs
CassandraRing topology needs ordering

When NOT to Use StatefulSets

ApplicationUse Instead
Stateless web appDeployment
App with shared storageDeployment + ReadWriteMany PVC
App without stable ID needsDeployment

The Operational Complexity

StatefulSets are harder to operate than Deployments:

ChallengeWhy
Ordered startupSlow if 100 replicas
PVC managementPVCs persist after deletion
Data migrationNo automatic data movement
BackupPer-Pod backup needed
DebuggingHarder 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

DaemonSetPurpose
kube-proxyNetworking
CNI pluginPod networking (Cilium, Calico)
CSI node pluginStorage
Fluent Bit / FilebeatLog collection
Prometheus Node ExporterNode metrics
Datadog / New Relic agentAPM
Falco / TetragonRuntime security
NVIDIA device pluginGPU 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

StrategyBehavior
RollingUpdateUpdate pods one node at a time
OnDeleteUpdate 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 CaseExample
Log collectionFluent Bit on every node
Metrics collectionnode-exporter on every node
NetworkingCilium agent on every node
StorageCSI node plugin on every node
SecurityFalco on every node
GPUNVIDIA 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

PatternDescription
SingleOne Pod runs to completion
Parallel fixedN Pods complete successfully
Work queueN workers process a queue
IndexedEach 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

ParameterPurposeDefault
completionsTotal successes needed1
parallelismMax concurrent Pods1
backoffLimitRetries before failure6
activeDeadlineSecondsTimeout for whole JobNone
ttlSecondsAfterFinishedAuto-delete after N secondsNone
completionModeNonIndexed or IndexedNonIndexed

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)
│ │ │ │ │
* * * * *
ScheduleMeaning
0 * * * *Every hour
0 0 * * *Every day at midnight
0 2 * * *Every day at 2 AM
0 0 * * 0Every Sunday
0 0 1 * *First of month
*/15 * * * *Every 15 minutes

Concurrency Policy

PolicyBehavior
AllowMultiple Jobs run concurrently
ForbidSkip if previous Job still running
ReplaceKill previous, start new

CronJob Best Practices

PracticeWhy
Set concurrencyPolicyPrevent overlap
Set startingDeadlineSecondsDon't run too late
Use activeDeadlineSecondsPrevent runaway jobs
Set resource limitsPredictable scheduling
Set ttlSecondsAfterFinishedAuto-cleanup
Use timeZoneCorrect scheduling
Idempotent jobsSafe 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

PhaseMeaning
PendingAccepted, waiting for scheduling or image pull
RunningAt least one container running
SucceededAll containers exited successfully (exit 0)
FailedAt least one container failed (exit ≠ 0)
UnknownCan't determine state (usually node issue)

Container States

StateMeaning
WaitingNot started (pulling image, waiting for dependency)
RunningExecuting
TerminatedFinished or crashed

Common Waiting Reasons

ReasonCause
ContainerCreatingRuntime is setting up
CrashLoopBackOffContainer keeps crashing
ImagePullBackOffCan't pull image
ErrImagePullImage pull error
CreateContainerConfigErrorBad config (missing ConfigMap/Secret)
CreateContainerErrorRuntime failed to create
RunContainerErrorContainer failed to start
PodInitializingInit 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

PolicyBehavior
AlwaysRestart on any exit (default for Deployments)
OnFailureRestart only on non-zero exit
NeverNever 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

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

The Lifecycle Interaction

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

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

Probe Mechanisms

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

HTTP Probe

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

TCP Probe

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

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

Exec Probe

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

Use for: Complex health checks, custom logic.

gRPC Probe (K8s 1.24+)

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

Requires gRPC Health Checking Protocol support in the app.

Probe Parameters

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

The Liveness Probe Anti-Pattern

DON'T make liveness probes dependent on external services:

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

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

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

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

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

Readiness Probe Patterns

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

Startup Probe Tuning

For slow-starting apps:

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

After startup succeeds, liveness and readiness probes begin.

Probe Best Practices

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

The Probe Debugging Workflow

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

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

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

8. Init Containers

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

Init Container Characteristics

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

Common Init Container Patterns

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

Example: Wait for Database

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

Example: Setup Config from Template

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

Init Container Failure

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

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

Init Container Anti-Patterns

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

9. Native Sidecar Containers (K8s 1.29+)

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

Traditional Sidecar Problems

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

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

Native Sidecar Containers

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

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

Key Differences

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

When to Use Native Sidecars

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

The Log Shipper Example

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

Behavior:

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

10. Ephemeral Containers

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

Why Ephemeral Containers

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

Creating an Ephemeral Container

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

Key flags:

What Ephemeral Containers Can See

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

The Debug Workflow

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

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

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

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

Debug Profiles

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

Security Considerations

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

RBAC for ephemeral containers:

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

Restrict this to debugging roles, not app teams.


11. Container Lifecycle Hooks

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

PostStart

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

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

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

PreStop

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

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

The PreStop Sleep Pattern

The most common production pattern:

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

Why it works:

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

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

HTTP PreStop

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

Tells the app to stop accepting new connections and drain.

PreStop Best Practices

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

The terminationGracePeriodSeconds Relationship

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

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


12. Graceful Shutdown and Termination

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

The Termination Flow

When a Pod is deleted:

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

terminationGracePeriodSeconds

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

The SIGTERM Handling Contract

Your app must:

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

Language-specific patterns:

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

Zero-Downtime Shutdown Checklist

The "Force Delete" Anti-Pattern

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

This bypasses graceful termination. It can:

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


13. Pod Disruption Budgets

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

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

Why PDBs Matter

Without PDB:

With PDB:

PDB Configuration

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

Or use maxUnavailable:

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

minAvailable vs maxUnavailable

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

Formula: minAvailable = replicas - maxUnavailable

For 3 replicas:

Percentage-Based

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

Scales with replica count.

Voluntary vs Involuntary Disruptions

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

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

The PDB Deadlock

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

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

PDB: minAvailable: 2

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

Solution: Ensure replicas are spread across nodes:

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

PDB Best Practices

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

Testing PDBs

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

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

# If PDB blocks, you'll see errors

14. Resource Management and QoS

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

QoS Classes

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

QoS Affects Restart Behavior

When a node is under memory pressure:

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

Guaranteed Workload

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

Best for: Databases, critical workloads.

Burstable Workload

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

Best for: Most web apps, APIs.

BestEffort Workload

yaml
# No resources section

Best for: Nothing production. Only dev/test.

QoS in Practice

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

15. Pod Overhead and Priority

Pod Overhead

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

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

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

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

Priority Classes

PriorityClass influences scheduling and preemption.

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

System priority classes (built-in):

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

Using Priority

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

Preemption

When a high-priority Pod can't schedule:

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

Preemption is disruptive. Use priority classes carefully.


16. Advanced Deployment Patterns

Blue/Green Deployments

Two identical environments, switch traffic atomically.

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

Cutover: Change the Service selector from blue to green.

Rollback: Change it back.

Canary Deployments

Deploy a small percentage of traffic to the new version.

Option 1: Two Deployments + Service

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

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

Option 2: Service Mesh (Istio)

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

Progressive Delivery

Combine canary with metrics analysis:

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

Argo Rollouts automates this with Prometheus analysis.


PART 3: PRODUCTION FAILURE MODES

17. Top 10 Workload Failures

#FailureSymptomRoot CauseFix
1CrashLoopBackOffPod keeps restartingApp crashesCheck logs, fix app
2ImagePullBackOffCan't pull imageBad tag, authFix image or secrets
3OOMKilledExit 137Memory limit exceededIncrease limit, fix leak
4Readiness probe failsPod never ReadyProbe or app issueFix probe or app
5PDB blocking drainCan't drain nodePDB too strictAdjust PDB
6StatefulSet stuckPods won't start in orderPod 0 unhealthyFix Pod 0
7Job never completesJob stuck runningNon-idempotent job, hook failureFix job logic
8PreStop hangsPod takes forever to terminatePreStop script bugFix preStop
9Slow rolloutUpdate takes hoursmaxUnavailable too low, probes too strictTune rollout
10Native sidecar incompatibilityPod fails to startK8s < 1.29Upgrade 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?

ComponentImpactSeverity
All replicas crashService downSEV-1
One replica crashDegraded capacitySEV-2
StatefulSet Pod 0 downCluster unavailableSEV-1
PDB blocks drainCan't upgrade clusterSEV-2
Job failsBatch incompleteSEV-3
CronJob failsMissed scheduleSEV-3
Probe misconfigurationTraffic to bad podsSEV-2

Mitigation Strategies

StrategyImplementation
Multiple replicas3+ for production
Pod anti-affinitySpread across nodes/AZs
Readiness probesNo traffic to bad pods
PodDisruptionBudgetsProtect during disruptions
Graceful shutdownNo dropped requests
Resource limitsPredictable 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

SignalAction
CPU throttling > 5%Increase CPU limit
OOMKilledIncrease 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

TargetArchitecture
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 TypeWorkloadReplicasStorageNotes
Stateless webDeployment3+NonePDB, probes, HPA
API serviceDeployment3+NoneSame
DatabaseStatefulSet1-3RWOAnti-affinity, backups
Message queueStatefulSet3+RWOCluster ID, no scale-to-0
CacheStatefulSet3+RWOMemory-optimized nodes
Batch jobJobN/AOptionalResource limits, backoff
Cron taskCronJobN/AOptionalIdempotent, timeouts
Node agentDaemonSetN/AHost mountTolerations, resources
Log collectorDaemonSetN/AHost mountSame

24. Migration Strategies

VM to Kubernetes Migration

PhaseAction
1. AssessInventory VMs, dependencies
2. ContainerizeBuild images, extract config
3. Deploy statelessStart with stateless services
4. Migrate statefulUse StatefulSets, external DBs
5. OptimizeRight-size, autoscale, tune
6. DecommissionRetire VMs

The 12-Factor App Fit

FactorKubernetes Support
CodebaseContainer images
DependenciesContainer isolation
ConfigConfigMaps, Secrets
Backing servicesServices, ExternalName
Build/release/runCI/CD + image tags
ProcessesStateless containers
Port bindingService abstraction
ConcurrencyHorizontal scaling
DisposabilityGraceful shutdown
Dev/prod paritySame images everywhere
Logsstdout/stderr
Admin processesJobs, CronJobs

25. Compliance & Security for Workloads

FrameworkWorkload Requirement
PCI-DSSNon-root, read-only rootfs, PSS restricted
HIPAAEncryption, audit, access controls
SOC2Change management, monitoring
FedRAMPFIPS 140-2, PSS restricted

Workload security checklist:


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

SeverityImpactResponse TimeEscalation
SEV-1All replicas down / service unavailable5 minOn-call + Platform + Management
SEV-2Degraded / partial outage15 minOn-call + Platform
SEV-3Single Pod issue1 hourOn-call
SEV-4Configuration warning4 hoursTicket

PART 8: INTERVIEW PREPARATION

38. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
DeploymentStateless, rolling updates, ReplicaSets
StatefulSetStable identity, per-Pod storage, ordered
DaemonSetOne Pod per node
JobRuns to completion
CronJobScheduled Jobs
Pod PhasesPending → Running → Succeeded/Failed
Container StatesWaiting → Running → Terminated
Startup ProbeSlow start; disables other probes
Liveness ProbeRestart on failure
Readiness ProbeRemove from service on failure
Init ContainersSequential setup
Native SidecarInit container with restartPolicy: Always
Ephemeral ContainerDebug without restart
PostStartRuns after container starts
PreStopRuns before SIGTERM
Graceful ShutdownpreStop + SIGTERM + grace period
terminationGracePeriodSecondsWait before SIGKILL (default 30)
PDBLimits voluntary disruptions
QoSGuaranteed > Burstable > BestEffort
PriorityClassScheduling 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)

DoesDoesn't Do
Watches for unscheduled PodsStart containers
Filters nodes by constraintsManage container lifecycle
Scores feasible nodesHandle networking
Binds Pod to nodeRun health checks
Triggers preemptionPull 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

SourceWhat It Provides
Pod specResource requests, affinity, tolerations, priority
Node statusAvailable resources, taints, labels, conditions
PV/PVC stateStorage availability
TopologyZones, 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

CycleWhat HappensCan Fail?
Scheduling CycleFilter + Score for one PodYes → retry or preempt
Binding CycleWrite nodeName to PodYes → 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:

QueuePurpose
ActiveQueuePods ready to be scheduled
BackoffQueuePods that failed scheduling (retry with backoff)
UnschedulableQueuePods 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

ProsCons
Very simple to writeNo soft preferences
Fast evaluationNo OR logic
Easy to understandPod stays Pending if no match
—No operators like In, NotIn

When to Use Node Selectors

ScenarioNode 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:

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

OperatorMeaning
InLabel value is in the list
NotInLabel value is not in the list
ExistsLabel exists (any value)
DoesNotExistLabel does not exist
GtLabel value > specified (numeric)
LtLabel 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

PatternPurpose
Zone spreadingRequired in specific zones
Hardware targetingGPU, NVMe, FPGA
Environment isolationDev/staging/prod nodes
Cost optimizationSpot vs on-demand
ComplianceData 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":

topologyKeyMeaning
kubernetes.io/hostnamePer node
topology.kubernetes.io/zonePer zone
topology.kubernetes.io/regionPer region
Custom labelCustom 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

OperationCost
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 versionsLower 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

GotchaImpact
Required anti-affinity with replicas > nodesPods stay Pending forever
Required affinity with no matching PodsPod stays Pending forever
Anti-affinity in small clustersCan't schedule multiple replicas
Affinity to selfCircular 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

ConceptWhere SetMeaning
TaintOn the Node"Don't schedule Pods here unless they tolerate this"
TolerationOn the Pod"I can be scheduled on nodes with this taint"

Taint Effects

EffectBehavior
NoScheduleNew Pods without toleration won't schedule here
PreferNoScheduleScheduler tries to avoid, but may schedule
NoExecuteEvicts 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

OperatorBehavior
EqualTaint key AND value must match
ExistsTaint 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

TaintPurpose
node.kubernetes.io/not-readyNode not ready
node.kubernetes.io/unreachableNode unreachable
node.kubernetes.io/memory-pressureMemory pressure
node.kubernetes.io/disk-pressureDisk pressure
node.kubernetes.io/pid-pressurePID pressure
node.kubernetes.io/network-unavailableNetwork unavailable
node.kubernetes.io/unschedulableNode cordoned
node-role.kubernetes.io/control-planeControl 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:

  1. New Pods without toleration → not scheduled
  2. 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?

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

PatternPurpose
Dedicated GPU nodesTaint GPU nodes; only GPU workloads tolerate
Dedicated monitoring nodesTaint monitoring; only monitoring tolerates
Spot node isolationTaint spot nodes; only batch tolerates
Control plane isolationBuilt-in taint on control plane
Node with issuesSystem 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

ClassValuePurpose
system-node-critical2000001000Node-level components (kube-proxy, CNI)
system-cluster-critical2000000000Cluster-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

  1. Queue order: Higher-priority Pods are scheduled first.
  2. Preemption: If a high-priority Pod can't schedule, lower-priority Pods may be preempted.

Preemption

When a high-priority Pod is Pending:

  1. Scheduler looks for nodes where the Pod would fit if some lower-priority Pods were removed.
  2. Picks the node that minimizes disruption.
  3. Marks lower-priority Pods for eviction.
  4. 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-PatternImpact
All Pods same priorityNo preemption benefit
Everything high priorityDefeats the purpose; races
Priority without PDBsPreemption kills critical Pods
Ignoring system prioritiesUser Pods can preempt control plane Pods (rare)

Priority Classes Design

PriorityUse Case
2000001000system-node-critical (reserved)
2000000000system-cluster-critical (reserved)
1000000Production user-facing APIs
100000Production backend services
10000Batch jobs, pipelines
1000Development workloads
0Default (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:

ParameterMeaning
maxSkewMaximum difference in Pod count between domains
topologyKeyNode label defining the domain
whenUnsatisfiableDoNotSchedule or ScheduleAnyway
labelSelectorWhich Pods to count
minDomainsMinimum 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

ValueBehavior
DoNotScheduleHard requirement — Pod stays Pending if constraint can't be met
ScheduleAnywaySoft 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

AspectTopology SpreadAnti-Affinity
Declarative✅ Yes⚠️ Less so
Balance✅ Even distribution❌ Only "not together"
ComplexitySimple maxSkewComplex selectors
PerformanceBetterCan be slow
Best forHA, balanced spreadStrict 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

ScenarioUse 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

ScenarioUse 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 PointPurpose
QueueSortSort Pods in the scheduling queue
PreFilterPre-process Pod info; check if feasible nodes exist
FilterEliminate infeasible nodes
PostFilterHandle unschedulable Pods (preemption)
PreScorePre-process scoring
ScoreScore each feasible node (0-100)
NormalizeScoreNormalize scores across plugins
ReserveReserve resources on the chosen node
PermitAllow/deny/wait before binding
PreBindPre-binding setup
BindFinalize 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

PluginExtension Points
NodeResourcesFitFilter, Score
NodeAffinityFilter, Score
PodTopologySpreadPreFilter, Filter, PreScore, Score
InterPodAffinityPreFilter, Filter, PreScore, Score
TaintTolerationFilter, Score
ImageLocalityScore
DefaultPreemptionPostFilter
VolumeBindingPreFilter, Filter, Reserve, PreBind

Custom Plugins

You can write your own plugins in Go and register them. Common use cases:

Use CasePlugin Type
Custom scoringScore
Hardware-aware placementFilter, Score
Custom preemptionPostFilter
Multi-tenant fairnessQueueSort, 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 CaseCustom Scheduler
Batch jobsGang scheduling, queue-based
ML trainingGPU-aware, gang, topology
HPCNUMA-aware, network topology
Specialized hardwareFPGA, TPU
Custom policiesBusiness rules

Deploying a Custom Scheduler

  1. Build a binary using the Scheduler Framework.
  2. Deploy it as a Deployment or static Pod.
  3. Register it with the API server (via ServiceAccount, RBAC).
  4. 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

SchedulerPurpose
VolcanoBatch AI/ML, gang scheduling
KueueJob queueing and quotas
YuniKornBig data, batch
Scheduler PluginsML, 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:

The Descheduler continuously looks for Pods that violate scheduling policies and evicts them, letting the scheduler re-place them.

Common Descheduler Strategies

StrategyPurpose
RemoveDuplicatesNo two replicas on the same node
LowNodeUtilizationBalance resource usage across nodes
HighNodeUtilizationPack workloads (for scale-to-zero)
RemovePodsViolatingInterPodAntiAffinityEnforce anti-affinity
RemovePodsViolatingNodeAffinityEnforce node affinity
RemovePodsViolatingNodeTaintsEnforce taints
RemovePodsViolatingTopologySpreadConstraintEnforce spread
RemovePodsHavingTooManyRestartsEvict crashlooping Pods
PodLifeTimeEvict 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

ComponentPurpose
Topology ManagerKubelet-level NUMA alignment
CPU ManagerStatic CPU allocation

Enabling Topology Manager

In /var/lib/kubelet/config.yaml:

yaml
topologyManagerPolicy: single-numa-node
cpuManagerPolicy: static

Restart kubelet.

The Topology Policies

PolicyBehavior
noneNo alignment
best-effortTry to align; don't fail
restrictedAlign if possible; fail if not
single-numa-nodeAll 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:

When to Use NUMA-Aware Scheduling

WorkloadNUMA-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:


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:

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

#FailureSymptomRoot CauseFix
1Pod stays Pendingkubectl get pods shows PendingNo node matches constraintsCheck describe Events
2Anti-affinity deadlockPods stuck PendingRequired anti-affinity + replicas > nodesUse preferred or add nodes
3Resource fragmentationNodes show free resources but Pods PendingFragmentation (no node has enough of a single resource)Bin-pack or add larger nodes
4Taint not toleratedPods PendingMissing tolerationAdd toleration
5PDB blocks drainNode drain hangsPDB too strictAdjust PDB or add nodes
6Scheduler overloadSlow schedulingToo many PodsScale scheduler, reduce churn
7Priority inversionLow-priority Pods preemptedWrong priority classesFix priorities
8Topology spread deadlockPods PendingmaxSkew too strictRelax maxSkew
9Volume binding delayPods stuck PendingPV in different zoneUse WaitForFirstConsumer
10Scheduler cache inconsistencyPods scheduled on full nodesStale cacheRestart 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 MessageMeaningFix
0/10 nodes are available: 5 Insufficient cpuResource shortageAdd nodes or reduce requests
node(s) had taint {key: value}, that the pod didn't tolerateTaint not toleratedAdd toleration
node(s) didn't match Pod's node affinityAffinity mismatchCheck labels
node(s) didn't match pod anti-affinity rulesAnti-affinity conflictRelax or add nodes
node(s) had volume node affinity conflictPV in wrong zoneUse WaitForFirstConsumer
pod has unbound immediate PersistentVolumeClaimsPVC not boundCheck PVC/StorageClass
0/10 nodes are available: 10 node(s) were unschedulableAll nodes cordonedUncordon

20. Blast Radius Analysis

What Happens When Scheduling Fails?

ComponentImpactSeverity
All new Pods PendingService can't scaleSEV-1
Single Pod PendingDegraded capacitySEV-2
Scheduler downAll new Pods PendingSEV-1
Node drain blocked by PDBUpgrade stuckSEV-2
Wrong priorityPreemption outagesSEV-2
FragmentationWasted capacitySEV-3

Mitigation Strategies

StrategyImplementation
Multiple scheduler replicasHA scheduling
Topology Spread (not Anti-Affinity)Better performance
Preferred over RequiredFlexibility
PDB designEnsure drainability
PriorityClassesClear priorities
DeschedulerRebalance

PART 4: CAPACITY PLANNING & COST MODELING

21. Bin-Packing vs Spreading

Spreading (Default)

The default scheduler spreads workloads (LeastAllocated).

ProsCons
Resilient to node failureLower utilization
Even distributionMore nodes needed
Simpler reasoningHigher 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
ProsCons
Higher utilizationLess resilient
Lower costRisk of cascading failure
Fewer nodesNoisy neighbors

When to Use Which

ScenarioStrategy
Production APIsSpreading
Batch jobsBin-packing
Cost-sensitiveBin-packing
Resilience-criticalSpreading
MixedDifferent 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:

Covered in depth in Stage 10 (Autoscaling).

Cost Visibility via Scheduling Metrics

MetricMeaning
kube_pod_container_resource_requestsPod requests
kube_node_status_allocatableNode capacity
kube_pod_status_phase{phase="Pending"}Pending Pods
scheduler_schedule_attempts_totalScheduling 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

TargetArchitecture
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 TypeIsolation Strategy
Internal teamsNamespaces + priorities + quotas
External customersSeparate node pools + taints
Hostile tenantsSeparate clusters
GPU tenantsDedicated 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:


26. Compliance & Security for Scheduling

FrameworkScheduling Requirement
PCI-DSSNetwork segmentation, dedicated nodes for cardholder data
HIPAAIsolated compute for PHI workloads
GDPRData residency (EU-only nodes)
FedRAMPDedicated 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

SeverityImpactResponse TimeEscalation
SEV-1All new Pods Pending / scheduler down5 minOn-call + Platform + Management
SEV-2Specific workload stuck Pending15 minOn-call + Platform
SEV-3Slow scheduling1 hourOn-call
SEV-4Configuration warning4 hoursTicket

PART 8: INTERVIEW PREPARATION

39. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
SchedulerFilter → Score → Bind
Node SelectorSimple, hard requirement
Node AffinityAdvanced, hard/soft, rich operators
Pod AffinityCo-locate with other Pods
Pod Anti-AffinityKeep apart from other Pods
TaintNode repels Pods
TolerationPod allows taint
NoScheduleNew Pods blocked
NoExecuteExisting Pods evicted
PriorityClassHigher priority + preemption
PreemptionEvict lower-priority Pods
Topology SpreadEven distribution across domains
maxSkewMax difference between domains
DoNotScheduleHard topology spread
ScheduleAnywaySoft topology spread
Scheduler FrameworkPlugin architecture
Custom SchedulerOwn binary, own rules
Scheduler ProfileMultiple schedulers in one binary
DeschedulerRebalance existing Pods
NUMA-AwareAlign CPU/memory to NUMA nodes
Bin-PackingMostAllocated scoring
SpreadingLeastAllocated 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

PrincipleMeaning
Zero-TrustNo implicit trust; verify everything
Least PrivilegeMinimum permissions necessary
Defense in DepthMultiple independent layers
Separation of DutiesNo single role has all power

2. Authentication

Authentication verifies the identity of the caller. The API server supports several methods.

Authentication Methods

MethodUse Case
X.509 Client CertificatesHuman admins, kubelet
ServiceAccount TokensWorkloads inside the cluster
OIDCEnterprise SSO (Okta, Azure AD, Google)
Webhook Token AuthenticationExternal auth service
Authenticating ProxyHeader-based (for proxies)
Bootstrap TokensNode bootstrap
Static Token FileLegacy (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

PrefixMeaning
system:Kubernetes internal
system:serviceaccount:<ns>:<name>ServiceAccount
system:node:<name>Kubelet
system:apiserverAPI server
(no prefix)External user

Authentication Best Practices

PracticeWhy
Use OIDC for humansCentralized, auditable
Rotate client certificatesShort-lived, limited blast radius
Disable static tokensDeprecated, hard to rotate
Disable anonymous authPrevent unauthorized access
Use bound ServiceAccount tokensAuto-rotated, audience-scoped
Audit all authenticationDetect anomalies

3. Authorization

Once authenticated, Kubernetes checks if the user is authorized to perform the requested action.

Authorization Modes

ModeDescriptionUse Case
RBACRole-Based Access ControlDefault, recommended
ABACAttribute-Based Access ControlLegacy, file-based
NodeNode authorizerKubelet authorization
WebhookExternal authorizationCustom policies
AlwaysAllowEverything is allowed❌ Never in production
AlwaysDenyEverything is deniedTesting

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

VerbAction
getRead one resource
listList resources
watchWatch for changes
createCreate new
updateUpdate existing (full)
patchUpdate (partial)
deleteDelete one
deletecollectionDelete many

The RBAC Resource Set

ResourceExample
podsCore Pod resources
pods/logPod subresource (logs)
pods/execPod subresource (exec)
deploymentsApps group
secretsSensitive
nodesCluster-level
configmapsNon-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

ObjectScopePurpose
RoleNamespacePermissions within a namespace
ClusterRoleClusterPermissions cluster-wide
RoleBindingNamespaceBind Role or ClusterRole to subjects
ClusterRoleBindingClusterBind 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

KindExample
Useralice, bob@example.com
Groupdevelopers, system:masters
ServiceAccountdefault/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:

ClusterRolePurpose
cluster-adminFull cluster access
adminNamespace admin (most resources)
editEdit most resources (no RBAC)
viewRead-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:

  1. Gather all Roles/ClusterRoles bound to the user via RoleBindings/ClusterRoleBindings.
  2. Check if any rule allows the request.
  3. 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)

NeedRole Rule
Read Podsresources: ["pods"], verbs: ["get", "list", "watch"]
Read Pod logsresources: ["pods/log"], verbs: ["get"]
Exec into Podsresources: ["pods/exec"], verbs: ["create"]
Port forwardresources: ["pods/portforward"], verbs: ["create"]
List Secretsresources: ["secrets"], verbs: ["list"]
Deployresources: ["deployments"], verbs: ["create", "update"]
Delete namespaceresources: ["namespaces"], verbs: ["delete"]

RBAC Anti-Patterns

Anti-PatternRisk
cluster-admin for humansFull cluster compromise
Wildcard verbs (*)Unintended permissions
Wildcard resources (*)Unintended scope
Binding cluster-admin via RoleBindingNamespace-wide admin
default ServiceAccount with permissionsEvery Pod gets it
No RBAC auditingDrift, 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:

These allow Pods to assume cloud IAM roles without static credentials.

Best Practices

PracticeWhy
One ServiceAccount per workloadLeast privilege
Disable auto-mount when not neededReduce attack surface
Use projected tokensAuto-rotated
Bind to minimal RBACLeast privilege
Audit ServiceAccount usageDetect anomalies
Never use defaultShared across namespace
Use workload identityNo 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

LevelRestrictivenessUse Case
PrivilegedUnrestrictedSystem workloads
BaselineMinimally restrictiveMost workloads
RestrictedHeavily restrictiveSecurity-critical

Privileged (No Restrictions)

Everything allowed. Only for cluster-admin workloads (CNI, monitoring, system components).

Baseline (Common Restrictions)

Blocks:

Allows:

Restricted (Maximum Security)

Everything in Baseline, plus:

Baseline vs Restricted Comparison

SettingBaselineRestricted
Privileged❌❌
Host namespaces❌❌
hostPath❌❌
Host ports❌❌
CapabilitiesLimitedDrop ALL
Privilege escalation❌❌
Non-rootOptionalRequired
Read-only rootfsOptionalRecommended
seccompOptionalRequired

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

ModeBehavior
enforceReject violating Pods
auditLog violations
warnShow 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:

  1. Audit only: audit=restricted, no enforcement
  2. Warn only: warn=restricted
  3. Enforce baseline: enforce=baseline
  4. 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

TypeCan Modify?Order
Mutating✅ YesFirst
Validating❌ NoSecond

Failure Policy

PolicyBehaviorWhen to Use
FailReject if webhook unreachableSecurity-critical
IgnoreAllow if webhook unreachableOptional 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-PatternRisk
failurePolicy: Fail with no HAWebhook outage → cluster outage
Webhooks for every resourceMassive overhead
Slow webhooks (> 1s)Cluster-wide slowdown
No timeoutRequests hang
Broad resource scopeUnintended 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

CRDPurpose
ConstraintTemplateDefines a policy type (Rego code)
ConstraintInstance 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

PolicyPurpose
Required labelsEnforce metadata
Allowed registriesImage policy
No privilegedPod security
Resource limitsGovernance
Namespace restrictionsMulti-tenancy

OPA Rego vs YAML

AspectOPA/RegoKyverno/YAML
LanguageRego (custom DSL)YAML
PowerVery highHigh
Learning curveSteepGentle
EcosystemCNCFKyverno
Best forComplex policiesKubernetes-native

10. Kyverno

Kyverno is a Kubernetes-native policy engine. Policies are written in YAML (no custom DSL).

The Two CRDs

CRDPurpose
ClusterPolicyCluster-wide policy
PolicyNamespace-scoped policy

Kyverno Rule Types

TypePurpose
validateAccept/deny resources
mutateModify resources
generateCreate resources
verifyImagesVerify 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

ActionBehavior
EnforceBlock violation
AuditLog only (report)

Kyverno Best Practices

PracticeWhy
Start with AuditDon't break workloads
Test in stagingPolicies can have bugs
Version-control policiesGitOps
Use background: trueRetroactive enforcement
Set validationFailureActionEnforce vs audit
Exclude system namespacesCNI, kube-system

11. Image Policy

Image policy governs which container images are allowed in the cluster.

The Three Layers

LayerToolPurpose
RegistryHarbor, ECRStore scanned images
AdmissionKyverno verifyImagesVerify signatures at deploy
RuntimeFalco, TetragonDetect 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

PracticeWhy
Sign all imagesProve provenance
Scan before signBlock vulnerabilities
Verify at admissionReject unsigned
Use SBOMSupply chain visibility
Pin by digestImmutability
Block :latestNon-deterministic

12. Secrets Management

Secrets in Kubernetes are base64-encoded, not encrypted by default. Production requires external secret management.

The Problem with Native Secrets

IssueImpact
Base64 (not encryption)Anyone with read access can decode
etcd storageDepends on etcd encryption
No rotationManual, error-prone
In GitLeaked into version history
In env varsVisible 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:

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:

MethodDescription
Vault Agent InjectorSidecar injects secrets
Vault Secrets OperatorSyncs Vault to K8s Secrets
CSI Secrets StoreMounts secrets as volumes
Vault APIDirect API access

Secrets Management Comparison

ApproachComplexitySecurityUse Case
Native SecretsLow⚠️ Base64Dev/test
Encryption at restMedium✅Basic hardening
Sealed SecretsLow✅GitOps
SOPSLow✅GitOps + KMS
External SecretsMedium✅✅Multi-cloud
VaultHigh✅✅✅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

FieldPurpose
runAsUserUID to run container
runAsGroupGID to run container
runAsNonRootRequire non-root
fsGroupVolume ownership group
supplementalGroupsExtra groups
allowPrivilegeEscalationPrevent suid, setuid
readOnlyRootFilesystemImmutable rootfs
privilegedFull privileges (never)
capabilitiesLinux capabilities
seccompProfileSyscall filtering
procMountProc 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

LevelWhat's Logged
NoneNothing
MetadataWho, what, when — no body
RequestMetadata + request body
RequestResponseMetadata + 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

ResourceLevelWhy
SecretsRequestResponseTrack access
RBACRequestDetect privilege changes
Authentication failuresMetadataDetect attacks
Exec/port-forwardMetadataTrack access
Pod creationMetadataWorkload 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

PracticeWhy
Log Secrets accessDetect data exfiltration
Log RBAC changesDetect privilege escalation
Ship to SIEMCentralized analysis
Retain 90+ daysCompliance
Alert on anomaliesDetect attacks
Protect audit logsAppend-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

CloudNameMechanism
AWSIRSAOIDC + IAM Role
GCPWorkload IdentityGKE SA + GCP SA
AzureAzure AD Workload IdentityOIDC + Azure AD

Best Practices

PracticeWhy
One SA per workloadLeast privilege
One IAM role per SAAudit clarity
Scoped IAM policiesLeast privilege
No static credentialsRotation-free
Audit IAM role usageCloudTrail

PART 3: PRODUCTION FAILURE MODES

17. Top 10 Kubernetes Security Failures

#FailureSymptomRoot CauseFix
1Over-privileged SALateral movementBroad RBACLeast privilege
2cluster-admin for humansFull compromiseConvenienceOIDC + scoped RBAC
3Secrets in GitCredentials leakedNo secrets managementSealed Secrets, SOPS
4Privileged containersContainer escapeNo PSS enforcementPSA restricted
5No NetworkPolicyLateral movementDefault allow-allDefault deny
6Anonymous auth enabledUnauthorized accessDefault configDisable
7Webhook failurePolicy: FailCluster outageWebhook downHA webhook
8Unrotated certificatesAuth failuresNo rotationkubeadm certs renew
9No audit loggingCan't investigateNot configuredEnable audit logs
10Image without signature verificationBackdoored imageNo verifyImagesKyverno 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)

IndicatorWhere to Look
Unexpected RBAC changesAudit logs
Anomalous API accessAudit logs
New ServiceAccount createdAudit logs
ClusterRoleBinding createdAudit logs
Secrets accessed outside hoursAudit logs
Unexpected kubectl execAudit logs
New IAM role assumptionCloudTrail (AWS), Cloud Audit Logs (GCP)

19. Blast Radius Analysis

What Happens When Security Fails?

ComponentImpactSeverity
cluster-admin compromisedFull cluster takeoverSEV-1
ServiceAccount compromisedDepends on RBACSEV-1 to SEV-3
Secret leakedDepends on secret scopeSEV-1 to SEV-3
Privileged container escapeNode compromiseSEV-1
Image backdoorFull service compromiseSEV-1
RBAC misconfigurationUnintended accessSEV-2
Webhook downBlocked admissionsSEV-2

Mitigation Strategies

StrategyImplementation
Least privilege RBACMinimal permissions
OIDC for humansCentralized identity
Pod Security StandardsRestricted enforcement
Network PoliciesDefault deny
Image signingcosign + admission
Audit loggingCentralized SIEM
Secret managementVault, External Secrets
Runtime securityFalco, Tetragon

PART 4: CAPACITY PLANNING & COST MODELING

20. Policy Engine Overhead Modeling

Webhook Overhead

Webhook TypeLatencyImpact
OPA Gatekeeper5-50msPer admission
Kyverno5-30msPer admission
Custom webhookVariesDepends on logic

The Admission Bottleneck

Every admission request goes through:

  1. Mutating webhooks
  2. Schema validation
  3. Validating admission policies
  4. Validating webhooks

Impact: For a cluster with 10 webhooks, each admission has ~50-200ms overhead.

Scaling Considerations

Cluster SizeWebhook Replicas
< 100 nodes2 replicas
100-500 nodes3-5 replicas
> 500 nodes5-10 replicas + PDB

Overhead Mitigation

StrategyImpact
Scope webhooks narrowlyFewer matches
Cache decisionsLower latency
Use ValidatingAdmissionPolicy (CEL)In-process, faster
Batch operationsFewer admissions

21. Security Tooling Cost Analysis

Runtime Security Cost

ToolDeploymentCost per Node
Falco (self-hosted)DaemonSetInfrastructure only
TetragonDaemonSetInfrastructure only
Datadog SecurityDaemonSet~$30/month
Sysdig SecureDaemonSetEnterprise pricing
AquaMultipleEnterprise pricing

Policy Engine Cost

ToolCost
OPA GatekeeperFree (open source)
KyvernoFree (open source)
Kyverno EnterpriseCommercial
Styra DASCommercial (OPA management)

Secrets Management Cost

ToolCost
Kubernetes SecretsFree
Sealed SecretsFree
SOPSFree (KMS costs)
External Secrets OperatorFree (backend costs)
HashiCorp VaultOSS free / Enterprise pricing
AWS Secrets Manager$0.40/secret/month + API calls

The TCO of a Security Incident

Incident TypeEstimated 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

TargetArchitecture
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

ComponentHA Requirement
Webhooks3+ replicas, PDB
OPA Gatekeeper3+ replicas
Kyverno3+ replicas
Vault3+ node cluster
Audit log backendReplicated

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 LevelMechanism
SoftNamespaces + RBAC + NetworkPolicy + Quotas
MediumAbove + Pod Security Standards (restricted)
HardvCluster or separate clusters
StrongestSeparate clusters, separate cloud accounts

Namespace Isolation Checklist


25. Compliance & Security Frameworks

FrameworkK8s Requirement
PCI-DSSRBAC, audit logs, encryption, network segmentation
HIPAAAudit trails, access controls, encryption
SOC2Change management, monitoring, incident response
GDPRData residency, access controls, right to erasure
FedRAMPFIPS 140-2, SELinux, no privileged, STIG

CIS Kubernetes Benchmark (Key Items)


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

SeverityImpactResponse TimeEscalation
SEV-1Confirmed breach / cluster-admin compromise5 minSecurity + Platform + Management + Legal
SEV-2Suspected RBAC abuse / policy violation15 minSecurity + Platform
SEV-3Compliance finding / misconfiguration1 hourSecurity
SEV-4Policy warning / drift4 hoursTicket

PART 8: INTERVIEW PREPARATION

38. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
AuthenticationWho are you? (certs, tokens, OIDC)
AuthorizationWhat can you do? (RBAC, webhooks)
AdmissionShould we allow? (mutating → validating)
RBACRole, ClusterRole, Bindings. Additive.
RoleNamespace-scoped permissions
ClusterRoleCluster-scoped permissions
RoleBindingBind Role or ClusterRole to subject in namespace
ClusterRoleBindingBind ClusterRole cluster-wide
ServiceAccountWorkload identity
IRSAAWS IAM via OIDC
PSAPod Security Standards (Privileged, Baseline, Restricted)
PodSecurity AdmissionEnforce PSS via labels
Mutating WebhookModifies resources
Validating WebhookAllows/denies
failurePolicyFail or Ignore
KyvernoYAML-native policy engine
OPA GatekeeperRego policy engine
Image Signingcosign sign + verify
External SecretsSync from Vault, AWS SM, etc.
Sealed SecretsEncrypt in Git
Audit LoggingWho did what
NetworkPolicyPod firewall (default deny)
SecurityContextrunAsNonRoot, capabilities, seccomp
Encryption at restetcd 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

RuleMeaning
1. Pod-to-PodAny Pod can reach any other Pod without NAT
2. Pod-to-ServicePods can reach Services via stable ClusterIP
3. Node-to-PodNodes can reach Pods without NAT
4. External-to-ServiceExternal 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:


2. CNI (Container Network Interface)

CNI is the plugin interface that Kubernetes uses to configure Pod networking.

What a CNI Plugin Does

FunctionDescription
IPAMAssigns IP addresses to Pods
veth pairsCreates virtual Ethernet pairs
RoutingPrograms cross-node routes
PolicyEnforces 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

CategoryExamplesApproach
OverlayFlannel (VXLAN)Encapsulates pod traffic
RoutingCalico (BGP)Programs routes natively
eBPFCiliumKernel-level networking
Cloud-nativeAWS VPC CNI, Azure CNIUses cloud VPC IPs
SimpleBridge, host-localBasic connectivity

CNI Requirements

RequirementWhy
Pod CIDRIP allocation range
Kernel modulesVXLAN, eBPF, etc.
Node permissionsNetwork 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

TypeAccessibilityUse Case
ClusterIPInternal onlyService-to-service
NodePortVia Node IP + portDevelopment, on-prem
LoadBalancerCloud LBProduction external
ExternalNameDNS aliasExternal services

ClusterIP (Default)

yaml
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  type: ClusterIP
  selector:
    app: web
  ports:
  - port: 80
    targetPort: 8080

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:

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

ModeMechanismScalability
iptablesiptables DNAT rulesPoor (linear with services)
IPVSIPVS virtual serversGood (hash-based)
nftablesnftables rulesModern (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:

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

ComponentPurpose
Service watcherWatches Service/Endpoint changes
Rule programmerWrites iptables/IPVS rules
Health checker(IPVS only) Probes backend health
Metrics exporterExposes Prometheus metrics

The kube-proxy Performance Problem

Even IPVS requires netfilter hooks and conntrack overhead. At high scale, this causes:

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

PluginPurpose
kubernetesServes cluster.local records
forwardForwards external queries
cacheCaches responses
healthHealth endpoint
prometheusMetrics
loopDetects forwarding loops
reloadAuto-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):

  1. api.stripe.com.default.svc.cluster.local → NXDOMAIN
  2. api.stripe.com.svc.cluster.local → NXDOMAIN
  3. api.stripe.com.cluster.local → NXDOMAIN
  4. api.stripe.com. → Success

One logical lookup = 4 wire queries.

NodeLocal DNSCache

NodeLocal DNSCache runs a DNS cache on every node as a DaemonSet.

BenefitExplanation
Bypasses conntrackUDP → TCP conversion
Eliminates 5s timeoutNo UDP conntrack race
Sub-ms cache hitsNever leaves the node
Reduces CoreDNS load80–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)

AspectDetails
ApproachVXLAN overlay
Policy❌ None
PerformanceGood, but encapsulation overhead
Use CaseK3s 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)

AspectDetails
ApproachBGP routing, iptables/eBPF
Policy✅ Excellent NetworkPolicy
PerformanceExcellent (no encapsulation by default)
Use CaseProduction, 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)

AspectDetails
ApproacheBPF (kernel-native)
Policy✅ L3/L4/L7
PerformanceBest (O(1) lookups)
Use CaseModern, high-performance

Cilium was purpose-built around eBPF. Every packet passes through eBPF programs attached to network interfaces. The architecture consists of:

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

AspectDetails
ApproachNative VPC IPs
Policy✅ (via Calico)
PerformanceExcellent (native VPC)
Use CaseAWS 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:

Modes:

ModeIP UsagePod Density
Secondary IP (default)1 IP per podLimited by ENI × IPs
Prefix Delegation/28 prefix per ENI slot~4-16× more pods
Custom NetworkingDifferent subnet for podsSeparate 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

CNIApproachPolicyPerformanceBest For
FlannelVXLAN overlay❌GoodSimple clusters
CalicoBGP, iptables/eBPF✅ FullExcellentPolicy-heavy
CiliumeBPF✅ L3/L4/L7BestModern, high-performance
AWS VPC CNINative VPC✅ (via Calico)ExcellentEKS
Azure CNINative VNET✅ExcellentAKS
GKE Dataplane V2Cilium-based✅BestGKE

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.

MetricCilium (eBPF)Calico (iptables)
Service routingO(1)O(n)
Throughput25% higherBaseline
CPU at scaleStableIncreases
LatencyLowerHigher

Cilium Features

FeatureDescription
kube-proxy replacementeBPF service load balancing
L7 policiesHTTP, gRPC, Kafka
HubbleFlow-level observability
Cluster MeshMulti-cluster networking
Service MeshSidecarless mesh
Runtime securityTetragon

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:

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

BenefitDescription
O(1) service lookupConstant regardless of service count
No conntrack raceEliminates UDP DNS timeout
DSR supportDirect Server Return
Maglev hashingBetter load distribution
Session affinity without conntrackSimpler, faster
Faster failoverEndpoint 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

PracticeWhy
Start with default deny per namespaceFoundation of zero-trust
Label everything consistentlyPolicies rely on selectors
Test in monitor mode firstAvoid breaking traffic
Enforce both ingress and egressEgress prevents exfiltration
Review effective policy regularlyDetect drift
Never flip the whole cluster at onceRoll out per namespace

NetworkPolicy Limitations

Native NetworkPolicies operate at L3/L4. They cannot:

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

ScenarioL7 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 IngressWith Ingress
One LoadBalancer per app (expensive)One external IP, many routes
No path-based routingPath and host-based routing
No TLS terminationCentralized TLS

Ingress Controller Comparison

ControllerPerformanceAuto TLSgRPCTCP/UDP
NGINX Ingress~20K RPScert-manager✅✅
Traefik~19K RPSBuilt-in✅✅
HAProxy Ingress~100K+ RPScert-manager✅✅
Envoy~18.5K RPScert-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

AnnotationPurpose
nginx.ingress.kubernetes.io/rewrite-targetRewrite path
nginx.ingress.kubernetes.io/ssl-redirectForce HTTPS
nginx.ingress.kubernetes.io/proxy-body-sizeMax upload
nginx.ingress.kubernetes.io/rate-limitRate limiting
cert-manager.io/cluster-issuerAuto TLS

12. Gateway API

The Gateway API is the official successor to Ingress.

Why Gateway API

Ingress limitations:

  1. Annotation overload — Advanced features require controller-specific annotations that are not portable.
  2. No role separation — The same resource defines infrastructure and application routing.
  3. Limited protocol support — Only HTTP/HTTPS. No TCP, UDP, or gRPC-native routing.
  4. No header-based routing — Cannot route based on headers without annotations.
  5. No traffic splitting — Canary deployments require non-standard annotations.

Gateway API Resources

ResourceOwnerPurpose
GatewayClassInfrastructureDefines the controller
GatewayInfrastructureListener configuration
HTTPRouteApplicationHTTP routing rules
GRPCRouteApplicationgRPC routing
TLSRouteApplicationTLS passthrough
ReferenceGrantApplicationCross-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

AspectIngressGateway API
StatusStable (maintenance mode)GA (recommended)
Role separation❌ No✅ Yes
Protocol supportHTTP/HTTPSHTTP, HTTPS, gRPC, TCP, UDP
Header routingAnnotations only✅ Native
Traffic splittingAnnotations only✅ Native
Cross-namespaceLimited✅ ReferenceGrant
PortabilityController-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

PhaseAction
1. PilotDeploy Gateway API for one service
2. ValidateTest routing, TLS, observability
3. ExpandMigrate more services
4. RetireRemove 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:

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:

StepWhat Happens
1Pod queries 169.254.20.10 (local link)
2NodeLocal DNSCache receives UDP
3Cache hit → answer locally (sub-ms)
4Cache miss → forward over TCP to CoreDNS
5TCP conntrack entries are short-lived

Result: Eliminates the 5-second timeout.

CoreDNS Metrics to Monitor

MetricWhat It Shows
coredns_dns_requests_totalTotal queries
coredns_dns_responses_totalResponses by rcode
coredns_cache_hits_totalCache hits
coredns_forward_requests_totalUpstream queries
coredns_dns_request_duration_secondsQuery latency

15. Headless Services

A Headless Service (clusterIP: None) returns Pod IPs directly instead of a ClusterIP.

How Headless Works

AspectNormal ServiceHeadless Service
ClusterIPVirtual IPNone
DNS returnsClusterIPAll Pod IPs
Load balancingkube-proxyClient-side
Use caseStatelessStatefulSets

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 CaseWhy Headless
StatefulSetsStable identity per Pod
DatabasesClients connect to specific replicas
Message queuesBrokers need stable IDs
Peer discoveryPods find each other directly

16. Multi-Cluster Networking

Cluster Mesh (Cilium)

Cilium's Cluster Mesh connects multiple Kubernetes clusters with:

Submariner

Submariner connects clusters across clouds and on-premises. It uses a gateway node in each cluster to establish tunnels.

Multi-Cluster Service Discovery

ApproachTool
Cluster MeshCilium
SubmarinerOpen source
Service MirroringAdmiralty
DNS-basedCoreDNS federation

PART 3: PRODUCTION FAILURE MODES

17. Top 10 Kubernetes Networking Failures

#FailureSymptomRoot CauseFix
1Service has no endpointsConnection refusedSelector mismatchFix labels
2DNS resolution fails"Name not resolved"CoreDNS down, ndotsCheck CoreDNS, NodeLocal
35-second DNS timeoutIntermittent 5s stallsconntrack raceNodeLocal DNSCache
4CNI pod not readyPods stuck PendingCNI daemonset downCheck CNI logs
5NetworkPolicy blocks trafficConnection timeoutOverly strict policyTest with allow-all
6IP exhaustionPods can't get IPsPod CIDR exhaustedExpand CIDR, prefix delegation
7Ingress 502 errorsBad GatewayBackend not readyCheck endpoints
8Cross-node traffic failsPods can't reach each otherRouting issueCheck CNI, node routes
9kube-proxy stale rulesService unreachableRule programming lagRestart kube-proxy
10Gateway API misconfiguration404 errorsWrong parentRefsCheck 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

SymptomFirst CheckThen
No endpointskubectl get endpointsFix selector
DNS failsCoreDNS podsNodeLocal DNSCache
502/503Backend readinessIngress logs
TimeoutNetworkPolicyCNI logs
Cross-node failNode routesCNI routing

19. Blast Radius Analysis

What Happens When Networking Fails?

ComponentImpactSeverity
CNI downAll new Pods can't networkSEV-1
CoreDNS downService discovery failsSEV-1
kube-proxy downServices unreachableSEV-1
Ingress downExternal access failsSEV-1
NetworkPolicy misconfigTraffic blockedSEV-2
IP exhaustionPods stuck PendingSEV-1
5s DNS timeoutIntermittent latencySEV-2

Mitigation Strategies

StrategyImplementation
HA CoreDNS3+ replicas, PDB
NodeLocal DNSCacheEliminates conntrack race
HA Ingress3+ replicas, anti-affinity
CNI HADaemonSet on every node
IP capacity planningMonitor CIDR utilization
NetworkPolicy testingAudit before enforce

PART 4: CAPACITY PLANNING & COST MODELING

20. CNI Performance and Overhead Modeling

CNI Overhead by Type

CNICPU per NodeMemory per NodeThroughput
FlannelLowLowGood
Calico (iptables)MediumMediumExcellent
Calico (eBPF)LowMediumExcellent
CiliumLowMediumBest
AWS VPC CNILowMediumExcellent

Pod IP Capacity

Modem5.largem5.xlargem5.4xlarge
Secondary IP2958234
Prefix Delegation110220880

CNI Selection Criteria

FactorWeight
PerformanceHigh
Policy featuresHigh
ObservabilityMedium
Operational complexityMedium
Cloud integrationHigh

21. Ingress Controller Capacity Planning

Throughput per Replica

ControllerRPS per ReplicaCPU per 10K RPS
NGINX20,0002 cores
Traefik19,0002 cores
HAProxy100,000+2 cores
Envoy18,5002 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

TargetArchitecture
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

RequirementRecommended CNI
New cluster (2026)Cilium
Policy-heavy, existingCalico
AWS EKSAWS VPC CNI (+ Calico for policy)
Azure AKSAzure CNI
GKEDataplane V2 (Cilium-based)
Simple, K3sFlannel
eBPF, no kube-proxyCilium

Recommendation for 2026: Cilium for new clusters (eBPF performance, L7 visibility).


25. Compliance & Security for Networking

FrameworkNetworking Requirement
PCI-DSSNetwork segmentation, default deny
HIPAAEncryption in transit, audit
SOC2Change management, monitoring
GDPRData residency
FedRAMPFIPS 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

SeverityImpactResponse TimeEscalation
SEV-1Cluster-wide networking / DNS outage5 minOn-call + Platform + Management
SEV-2Service unreachable / partial outage15 minOn-call + Platform
SEV-3Single service issue1 hourOn-call
SEV-4Configuration warning4 hoursTicket

PART 8: INTERVIEW PREPARATION

38. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
CNIPlugin for Pod networking
FlannelSimple VXLAN, no policy
CalicoBGP, excellent policy
CiliumeBPF, best performance, L7
AWS VPC CNINative VPC IPs, prefix delegation
ClusterIPInternal Service VIP
NodePortExternal via node port
LoadBalancerCloud LB
ExternalNameDNS alias
kube-proxyService load balancing
iptablesLinear rules, poor scale
IPVSHash tables, better scale
eBPF replacementO(1) lookups, best
CoreDNSCluster DNS
ndots:5Search domain expansion
NodeLocal DNSCacheFixes 5s timeout
NetworkPolicyL3/L4 pod firewall
CiliumNetworkPolicyL7 (HTTP, gRPC)
Default denyZero-trust baseline
IngressHTTP routing (maintenance mode)
Gateway APISuccessor to Ingress
Headless ServiceReturns Pod IPs
Cluster MeshMulti-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

ObjectPurposeCreated By
PersistentVolume (PV)The actual storage resourceAdmin (static) or CSI driver (dynamic)
PersistentVolumeClaim (PVC)The application's request for storageApplication developer
StorageClassThe policy template for provisioningCluster 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 AbstractionWith Abstraction
App knows about EBS, GCP PD, NFSApp knows only about PVC
Changing storage = changing appChanging storage = changing StorageClass
No portabilityPortable across clusters
No access controlRBAC for storage

The Five Questions

When choosing storage, answer these five questions:

  1. Data path type: Block, file, or object-adjacent?
  2. Concurrent access: How many Pods need to read/write?
  3. Performance: What latency and throughput profile?
  4. Failure domain: Node, zone, or region?
  5. 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:

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

DriverCloudStorage Type
ebs.csi.aws.comAWSBlock (EBS)
efs.csi.aws.comAWSFile (EFS)
pd.csi.storage.gke.ioGCPBlock (Persistent Disk)
filestore.csi.storage.gke.ioGCPFile (Filestore)
disk.csi.azure.comAzureBlock (Azure Disk)
file.csi.azure.comAzureFile (Azure Files)
cephfs.csi.ceph.comOn-premFile (CephFS)
rbd.csi.ceph.comOn-premBlock (Ceph RBD)
driver.longhorn.ioOn-premBlock (Longhorn)

2026 Recommendations:


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

PhaseMeaning
AvailableNot yet bound to a PVC
BoundBound to a PVC
ReleasedPVC deleted, PV not yet reclaimed
FailedAutomatic 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

PolicyBehavior
RetainData preserved after PVC deletion; manual cleanup required
DeletePV and underlying storage deleted
RecycleDeprecated; basic scrub

Volume Modes

ModeBehavior
FilesystemMounted as a directory (default)
BlockRaw 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

StatusMeaning
PendingNot yet bound
BoundBound to a PV
LostPV 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

ParameterPurpose
provisionerCSI driver to use
parametersDriver-specific settings (type, IOPS, encryption)
reclaimPolicyDelete or Retain
allowVolumeExpansionEnable online resize
volumeBindingModeImmediate or WaitForFirstConsumer

Volume Binding Modes

ModeBehavior
ImmediateProvision before Pod scheduling
WaitForFirstConsumerProvision 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

PracticeWhy
Use WaitForFirstConsumerTopology-aware provisioning
Enable allowVolumeExpansionOnline resize
Set reclaimPolicy: RetainData safety for critical workloads
Multiple classesDifferent performance tiers
Mount optionsPerformance 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

ModeAbbreviationMeaning
ReadWriteOnceRWOMounted read-write by a single node
ReadOnlyManyROXMounted read-only by many nodes
ReadWriteManyRWXMounted read-write by many nodes
ReadWriteOncePodRWOPMounted read-write by a single Pod

Access Mode by Storage Type

Storage TypeRWOROXRWXRWOP
Block (EBS, PD, Azure Disk)✅❌❌✅
File (EFS, Filestore, Azure Files)✅✅✅✅
Ceph RBD✅✅❌✅
CephFS✅✅✅✅
Longhorn✅❌✅✅
Local PV✅❌❌✅

When to Use Each

Use CaseAccess Mode
Database (PostgreSQL, MySQL)RWO
Message queue (Kafka)RWO
Shared CMS mediaRWX
Read-only configROX
Single Pod with strict isolationRWOP

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

ObjectPurpose
VolumeSnapshotClassSnapshot policy (driver, parameters)
VolumeSnapshotThe snapshot itself
VolumeSnapshotContentThe 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

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.

AspectSnapshotBackup
LocationSame storage clusterDifferent location
ProtectionAgainst accidental deletionAgainst full storage failure
RetentionShort-termLong-term
ToolCSI SnapshotVelero, 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

ApplicationVolumes
PostgreSQLData volume + WAL volume
MySQLData volume + Binlog volume
MongoDBData volume + Journal volume
ElasticsearchData 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

  1. Kubernetes 1.24+
  2. StorageClass with allowVolumeExpansion: true
  3. CSI driver that supports expansion
  4. 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

TypeRequires Pod Restart?Support
Online❌ NoMost modern CSI drivers
Offline✅ YesOlder 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

TypeManaged ByUse Case
emptyDirKubernetesScratch space, caching
Generic ephemeralKubernetesPer-Pod storage
CSI ephemeralCSI driverInline 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

ScenarioLocal 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

LimitationImpact
No HANode failure = data loss
No replicationManual backup required
Node affinityPods must schedule to the right node
No expansionCapacity 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 CaseBenefit
AI/ML modelsPull models without init containers
Configuration bundlesVersioned configs via OCI
Static assetsMount frontend builds
WebAssembly modulesDistribute 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:

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

OptionEffectUse Case
noatimeDon't update access timeRead-heavy workloads
nodiratimeDon't update directory access timeSame as noatime
nconnectMultiple TCP connections (NFS)High throughput
rsize / wsizeRead/write size (NFS)Performance tuning
actimeoAttribute cache timeoutMetadata-heavy workloads
nodiratimeNo directory atimePerformance

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

WorkloadMount Options
Databasenoatime, nodiratime
NFS file sharenconnect=4, rsize=256K, wsize=256K
Read-only contentnoatime, ro
High-throughputnconnect=8

PART 3: PRODUCTION FAILURE MODES

16. Top 10 Storage Failures

#FailureSymptomRoot CauseFix
1PVC stuck PendingPVC never bindsNo matching PV, StorageClass issueCheck describe Events
2Volume attach failurePod stuck ContainerCreatingVolume in wrong zone, node limitCheck Events, zone
3Volume mount failurePod fails to startFilesystem corruption, mount optionsCheck Events, node logs
4Expansion failurePVC resize stuckDriver doesn't support, filesystem issueCheck Events, driver
5Snapshot creation failureSnapshot stuckSnapshotClass missing, driver issueCheck Events, CRDs
6Data lossData gone after PVC deleteDelete reclaim policyUse Retain
7Volume stuck in ReleasedPV not reusableRetain policy, manual cleanup neededDelete PV manually
8IOPS throttlingSlow performanceStorage limitsIncrease IOPS tier
9Zone mismatchPod can't mountPod and volume in different zonesUse WaitForFirstConsumer
10Local PV node failureData unavailableNode-local storageBackup, 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

SymptomFirst CheckThen
PVC Pendingkubectl describe pvcCheck StorageClass
Volume attach failkubectl get volumeattachmentsCheck zone
Mount failPod EventsNode logs
Expansion stuckkubectl describe pvcCheck driver support
Snapshot failkubectl describe volumesnapshotCheck SnapshotClass

18. Blast Radius Analysis

What Happens When Storage Fails?

ComponentImpactSeverity
Storage backend downAll stateful workloads failSEV-1
CSI driver downNew volumes can't provisionSEV-1
Volume attach failurePods stuckSEV-2
Data corruptionData lossSEV-1
Zone failureZonal volumes unavailableSEV-1
Snapshot failureBackup gapsSEV-2

Mitigation Strategies

StrategyImplementation
Replicated storageCeph, Longhorn
Regular backupsVelero
SnapshotsFast recovery
Multi-AZZone-aware provisioning
Retain policyPrevent 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 TypeIOPS per GBLatency
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

TierIOPSThroughputUse Case
Standard50050 MB/sDev/test
Performance3,000–16,000125–500 MB/sProduction
Ultra64,000+1,000+ MB/sDatabases, AI

20. Storage Tiering and Cost Optimization

Storage Tiers

TierTypeCost/GBUse Case
HotSSD/NVMe$$$Databases, active data
WarmSSD$$Web apps
ColdHDD$Archives
ArchiveObject¢Long-term retention

Cost Optimization Tactics

TacticSavings
Right-size volumes30–50%
Delete orphaned PVCs20–40%
Use gp3 instead of gp220%
Use snapshots for backups50% vs full copies
Tier cold data60–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

TargetArchitecture
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

MetricMeaningDepends On
RPO (Recovery Point Objective)Max data lossBackup frequency
RTO (Recovery Time Objective)Max downtimeRecovery speed
StrategyRPORTO
SnapshotsMinutesMinutes
VeleroHoursHours
ReplicationSecondsMinutes
Active-ActiveZeroZero

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

StrategyRPORTOCost
Backup/RestoreHoursHours$
SnapshotMinutesMinutes$$
ReplicationSecondsMinutes$$$
Active-ActiveZeroZero$$$$

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

PracticeWhy
Back up regularlyRPO
Test restoresVerify backups work
Store offsiteProtect against site failure
Encrypt backupsSecurity
AutomateConsistency

24. Compliance & Security for Storage

FrameworkStorage Requirement
PCI-DSSEncryption at rest, access controls
HIPAAEncryption, audit trails
SOC2Change management, monitoring
GDPRData residency, right to erasure
FedRAMPFIPS 140-2 encryption

Encryption

LayerHow
At restStorage encryption (EBS, PD, Azure Disk)
In transitTLS for network storage
Kubernetes Secretsetcd 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

SeverityImpactResponse TimeEscalation
SEV-1Data loss / all stateful workloads down5 minOn-call + Platform + Management
SEV-2Single PVC stuck / expansion failure15 minOn-call + Platform
SEV-3Slow storage performance1 hourOn-call
SEV-4Capacity planning warning4 hoursTicket

PART 8: INTERVIEW PREPARATION

37. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
PVStorage resource (admin-created)
PVCApplication request for storage
StorageClassTemplate for dynamic provisioning
CSIStandard plugin model for storage
RWOSingle node read-write
ROXMany nodes read-only
RWXMany nodes read-write
RWOPSingle Pod read-write
VolumeSnapshotPoint-in-time copy
VolumeGroupSnapshotAtomic multi-volume (K8s 1.36 GA)
ExpansionOnline resize with allowVolumeExpansion
emptyDirEphemeral scratch space
Generic ephemeralPer-Pod PVC
Local PVNode-local storage (high performance)
OCI VolumeSourceMount OCI artifacts (K8s 1.36 GA)
DRADynamic Resource Allocation (GA)
VeleroBackup and restore
RetainPreserve data after PVC delete
DeleteDelete storage after PVC delete
WaitForFirstConsumerZone-aware provisioning
nconnectMultiple NFS connections
Snapshots ≠ BackupsSnapshots 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

MechanismWhat It ExtendsUse Case
Custom Resource Definitions (CRDs)The APINew resource types
Admission WebhooksThe request pipelineValidation, mutation
Aggregation LayerThe API serverFull custom API servers

Why Extensibility Matters

Without ExtensibilityWith Extensibility
Fork Kubernetes for new featuresAdd features via CRDs
Wait for upstream releasesShip features independently
Limited to core resourcesUnlimited custom resources
No domain-specific automationOperators 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:

ValidationExample
Typetype: string
Requiredrequired: [image, replicas]
Minimum/Maximumminimum: 1, maximum: 100
Patternpattern: "^[a-z0-9-]+$"
Enumenum: [dev, staging, prod]
Defaultdefault: 1

CRD Scopes

ScopeBehavior
NamespacedCRs exist in namespaces
ClusterCRs are cluster-wide

CRD Best Practices

PracticeWhy
Use OpenAPI schemaValidation, documentation
Enable status subresourceSeparate spec from status
Set additionalPrinterColumnsBetter kubectl get output
Use shortNamesConvenience
Version from the startPlan for evolution
Avoid over-nestingKeep 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:

  1. Watches the API server for changes to specific resources
  2. Maintains a local cache (Indexer) for fast reads
  3. 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:

FeaturePurpose
Rate limitingPrevents overwhelming the controller
DeduplicationCollapses multiple events for the same object
RetryRe-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

GuaranteeMeaning
Level-triggeredReconcile runs on the current state, not events
IdempotentRunning multiple times produces the same result
Eventually consistentThe system converges to desired state
Optimistic concurrencyUses 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 ControllerOperator
Manages one resource typeManages a complex application
Generic logicDomain-specific knowledge
No external coordinationCoordinates multiple resources
Example: ReplicaSet controllerExample: 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

OperationWhat It Does
DeploymentCreates and configures all resources
ScalingAdjusts replicas based on load
BackupScheduled backups to object storage
RestorePoint-in-time recovery
UpgradeOrchestrates rolling upgrades
FailoverPromotes replicas on primary failure
ConfigurationManages config changes safely

Operator Maturity Model

LevelCapability
1. Basic InstallAutomated provisioning
2. Seamless UpgradesPatch and minor upgrades
3. Full LifecycleBackup, restore, failover
4. Deep InsightsMetrics, alerts, logs
5. Auto PilotAuto-scaling, auto-tuning, auto-recovery

When to Build an Operator

ScenarioBuild 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

OperatorPurpose
Prometheus OperatorManages Prometheus, Alertmanager, ServiceMonitors
cert-managerAutomates TLS certificate management
Istio OperatorManages Istio service mesh
PostgreSQL OperatorManages PostgreSQL clusters
Kafka OperatorManages Kafka clusters
CrossplaneManages 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

TypePurposeCan Modify?Order
MutatingModify objects✅ YesFirst
ValidatingAllow/deny❌ NoSecond
ConversionConvert between CRD versions✅ YesDuring 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 TypeWhere to Put It
Required labelsValidatingAdmissionPolicy (CEL)
Registry allowlistsValidatingAdmissionPolicy (CEL)
Resource limitsValidatingAdmissionPolicy (CEL)
Privileged container banValidatingAdmissionPolicy (CEL)
Image signature verificationValidating Webhook (external lookup)
Sidecar injectionMutating Webhook
Image digest pinningMutating 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

PolicyBehaviorWhen to Use
FailReject if webhook unreachableSecurity-critical
IgnoreAllow if webhook unreachableOptional 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

MarkerPurpose
+kubebuilder:subresource:statusEnable status subresource
+kubebuilder:subresource:scaleEnable scale subresource
+kubebuilder:validation:Minimum=1Minimum value
+kubebuilder:validation:Maximum=100Maximum value
+kubebuilder:default=1Default value
+kubebuilder:printcolumnAdditional printer columns
+kubebuilder:webhookGenerate webhook config

Operator SDK vs Kubebuilder

AspectOperator SDKKubebuilder
MaintainerRed HatKubernetes SIG
Corecontroller-runtimecontroller-runtime
CLIoperator-sdkkubebuilder
ScaffoldingMore optionsSimpler
OLMBuilt-inAdd-on
Best ForEnterprise, OLMGeneral 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

SettingMeaning
served: trueAPI accepts this version
storage: truePrimary 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

PracticeWhy
Start with v1alpha1Signal instability
Graduate to v1Stable API
Never change v1 schemaCompatibility
Use conversion webhooksMulti-version support
Test conversion pathsPrevent 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:

  1. User deletes object
  2. Object is marked deletionTimestamp
  3. Controller sees finalizer, performs cleanup
  4. Controller removes finalizer
  5. 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 ApplyServer-Side Apply
Uses last-applied annotationUses managedFields
Whole-resource conflictsField-level conflicts
Hard with multiple controllersNatural 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

BenefitWhy
Field ownershipKnow which controller owns which field
Conflict detectionDetect when another controller modifies your fields
Multi-controllerMultiple controllers can manage the same resource
IdempotentApply is naturally idempotent

10. Operator Lifecycle Manager (OLM)

OLM manages the lifecycle of operators in a cluster.

OLM Components

ComponentPurpose
OLM OperatorManages CSV lifecycle
Catalog OperatorResolves dependencies
CatalogSourceSource of operator bundles
SubscriptionRequest to install an operator
ClusterServiceVersion (CSV)Operator metadata
InstallPlanStep-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

BenefitWhy
Dependency resolutionAutomatically installs CRDs
UpgradesSafe operator upgrades
Multi-tenancyOperator scoping
CatalogDiscoverable 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

LevelToolPurpose
UnitGo testingIndividual functions
IntegrationenvtestController against real API server
E2EKUTTLFull cluster scenarios
FuzzingGo fuzzingCRD 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

CRDPurpose
PrometheusPrometheus instance
AlertmanagerAlertmanager instance
ServiceMonitorScrape configuration
PodMonitorPod scrape configuration
PrometheusRuleAlerting rules

cert-manager

CRDPurpose
CertificateTLS certificate request
IssuerNamespace-scoped CA
ClusterIssuerCluster-scoped CA
CertificateRequestActual CSR

Istio Operator

CRDPurpose
IstioOperatorIstio installation config
VirtualServiceTraffic routing
DestinationRuleLoad balancing
GatewayIngress/egress

PART 3: PRODUCTION FAILURE MODES

14. Top 10 Extensibility Failures

#FailureSymptomRoot CauseFix
1Webhook outageAPI requests failWebhook down, failurePolicy: FailHA webhook, adjust policy
2CRD version mismatchObjects can't be readConversion webhook brokenFix conversion logic
3Controller crash loopNo reconciliationBug in ReconcileFix code, add retries
4Finalizer stuckObject can't be deletedCleanup failsRemove finalizer manually
5OwnerReference cycleGarbage collection failsCircular referencesFix ownership graph
6Operator OOMController killedMemory leakIncrease limits, fix leak
7CRD schema too strictValid objects rejectedOver-validationRelax schema
8Webhook timeoutSlow API callsWebhook too slowOptimize webhook
9Operator RBAC insufficientPermission deniedMissing permissionsAdd RBAC rules
10CRD storage version changeData lossStorage migration failureTest 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?

ComponentImpactSeverity
Validating webhook down (Fail)All matching API requests failSEV-1
Mutating webhook down (Fail)All matching API requests failSEV-1
Conversion webhook downCRs with multiple versions failSEV-2
Operator crash loopNo automation; existing resources remainSEV-2
CRD schema bugValid objects rejectedSEV-2
Finalizer stuckResources can't be deletedSEV-3
Operator OOMController killedSEV-2

Mitigation Strategies

StrategyImplementation
HA webhooks3+ replicas, PDB
failurePolicy: IgnoreFor non-critical webhooks
Operator resource limitsPrevent OOM
Conversion testingTest all version paths
Finalizer timeoutNever block forever

PART 4: CAPACITY PLANNING & COST MODELING

17. Operator Resource Overhead

Typical Operator Resource Usage

ComponentCPU RequestMemory RequestReplicas
controller-runtime100m128Mi1-3
Webhook server100m128Mi3 (HA)
Prometheus Operator200m256Mi1
cert-manager100m128Mi1

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 TypeLatencyThroughput
ValidatingAdmissionPolicy (CEL)<1msUnlimited
Simple validating webhook5-20ms~500/s
Complex webhook50-200ms~50/s
Image verification100-500ms~20/s

18. CRD Storage Impact on etcd

CRD Storage Considerations

FactorImpact
CR countMore objects = more storage
CR sizeStatus updates increase size
Version countMore versions = more storage
Update frequencyMore writes = more etcd load

etcd Capacity Planning

CR CountCR SizeEstimated Storage
10010 KB1 MB
1,00010 KB10 MB
10,00010 KB100 MB
100,00010 KB1 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

TargetArchitecture
99.9%Single operator replica
99.99%2+ replicas, leader election, HA webhooks
99.999%Above + chaos testing, multi-cluster

Webhook HA Requirements

RequirementWhy
3+ replicasSurvive zone failure
PodDisruptionBudgetPrevent all replicas down
Pod anti-affinitySpread across nodes
Service with local trafficReduce latency

PART 5: ARCHITECTURE & STRATEGY

20. When to Build an Operator

Decision Framework

FactorBuild OperatorUse 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-PatternWhy It's Bad
Operator for everythingOverhead, complexity
No testingBugs in production
No observabilityCan't debug
cluster-admin RBACSecurity risk
No leader electionSplit 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

PracticeWhy
Least privilege RBACMinimize blast radius
Non-root containerSecurity
Read-only rootfsImmutability
seccomp RuntimeDefaultSyscall filtering
NetworkPolicyRestrict traffic
Webhook TLSEncrypted communication

22. Compliance & Security for Extensibility

FrameworkRequirement
PCI-DSSRBAC, audit logs, no privileged
HIPAAAudit trails, access controls
SOC2Change management, monitoring
FedRAMPFIPS 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

SeverityImpactResponse TimeEscalation
SEV-1Webhook blocking all API requests5 minOn-call + Platform + Management
SEV-2Operator crash loop / partial failure15 minOn-call + Platform
SEV-3Single CR stuck1 hourOn-call
SEV-4Configuration warning4 hoursTicket

PART 8: INTERVIEW PREPARATION

35. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
CRDCustom Resource Definition — extends API
CRCustom Resource — instance of a CRD
ControllerWatch-Queue-Reconcile loop
InformerWatches API, caches, enqueues
WorkQueueRate-limited, deduplicated queue
ReconcilerContains the control logic
OperatorController with domain knowledge
Admission WebhookIntercepts API requests
Mutating WebhookModifies objects
Validating WebhookAllows/denies
Conversion WebhookConverts CRD versions
ValidatingAdmissionPolicyCEL-based in-process policy (GA 1.32)
MutatingAdmissionPolicyCEL-based in-process mutation (Beta 1.33)
FinalizerPrevents deletion until cleanup
OwnerReferenceCascading deletion
Server-Side ApplyField-level ownership
OLMOperator Lifecycle Manager
KubebuilderOperator framework
envtestIntegration testing
KUTTLE2E 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

MetricValueSource
Clusters over-provisioning CPU69% (up from 40% two years prior)Cast AI 2026 State of Kubernetes report
Average CPU utilization8%Cast AI 2026
Container costs going to idle resources83%Datadog
Mid-sized platform team waste$45,000+ per monthZesty

Why Defaults Waste Money

Default BehaviorCost Impact
LeastAllocated scoringSpreads pods, leaves nodes underutilized
Resource requests ignoredScheduler uses requests, not actual usage
No consolidationIdle nodes stay running
No spot integrationPay full on-demand price
No cost visibilityCan't optimize what you can't see

The Three Levers

LeverToolImpact
RightsizingVPA, GoldilocksMatch requests to actual usage
ScalingHPA, KEDAMatch replicas to demand
PlacementBin-packing, KarpenterPack workloads densely
PricingSpot instancesPay 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

NumberMeaningUsed By
RequestMinimum resources guaranteedScheduler
LimitMaximum resources allowedKernel (cgroups)
Actual usageWhat the workload really consumesMonitoring

The gap between these three numbers is where cost and reliability problems show up.

The Cost Impact

ScenarioRequestActualWaste
Over-requested2 CPU200m90% waste
Under-requested100m500mThrottling, OOMKills
Right-sized300m250mMinimal 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

QoSRequests vs LimitsEviction PriorityCost
Guaranteedrequests == limitsLastHighest
Burstablerequests < limitsMiddleMedium
BestEffortNo requests/limitsFirstLowest

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

PracticeWhy
Set appropriate stabilization windowsPrevent thrashing
Use behavior policiesControl scale-up/down speed
Combine with VPA for right-sized podsEnsure requests are accurate
Monitor HPA decisionskubectl 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

LimitationImpact
CPU-based only (default)Doesn't work for queue-based workloads
Reacts to metrics15-second interval; not instantaneous
No scale-to-zeroMinimum replicas must be ≥ 1
Conflicts with VPAIf 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

ModeBehavior
OffRecommendations only (no changes)
InitialSet requests on Pod creation
AutoEvict and recreate Pods to apply

VPA Best Practices

PracticeWhy
Run in recommendation mode for 7 daysGet accurate data
Never run VPA Auto alongside HPA on the same CPU metricThey will fight each other
Use VPA for memory right-sizingMemory is less variable than CPU
Set min/max boundsPrevent 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

AspectScaledObjectScaledJob
TargetDeployment/StatefulSetJob
Use caseContinuous throughputDiscrete tasks
Scale to zero✅✅ (after completion)
ConcurrencyPool of replicasOne 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

CategorySources
Message QueuesKafka, RabbitMQ, SQS, Azure Service Bus
DatabasesPostgreSQL, MySQL, MongoDB
CloudAWS CloudWatch, Azure Monitor, GCP Pub/Sub
HTTPHTTP endpoints
MetricsPrometheus, 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

LimitationImpact
Node groupsPre-defined instance types only
Slow scale-up3–4 minutes
No repackingDoesn’t consolidate existing workloads
Request-basedInflated requests look like real demand
GKE only optionOn 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

DimensionKarpenterCluster Autoscaler
Provisioning45–60 seconds3–4 minutes
Instance selectionAny type (cheapest fitting)Pre-defined node groups
Consolidation✅ Active repacking❌ Does not repack
Spot supportNative, automatic fallbackSeparate ASGs, manual
GKE support❌ No official provider✅ Only option
AWS EKSDefault engine in EKS Auto ModeLegacy
Azure AKSGA in early 2026Legacy

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

CloudNotice Period
AWS2 minutes
Azure30 seconds
GCP30 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-SafeAvoid Spot
Stateless web servicesSingle-instance databases
Batch processing jobsStateful apps without replication
CI/CD build agentsReal-time processing
Dev/test environmentsLong-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

PracticeWhy
Diversify instance typesReduces interruption frequency
Use multiple AZsCapacity is regional
Set PDBsEnsure availability during interruptions
Graceful shutdownHandle 2-minute termination notice
Mix on-demand + spotFallback 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

LayerWhat It DoesWhen It Happens
Bin-packingScheduling decisionPod placement time
ConsolidationRemoves idle nodesOngoing

Both layers are necessary for sustained cost reduction.

The Consolidation Engines

EngineHow It Works
KarpenterActive consolidation, direct cloud API
Cast AI EvictorEvicts pods from underutilized nodes
DeschedulerEvicts pods violating policies

10. Cost Monitoring Tools

Kubecost vs OpenCost

AspectKubecostOpenCost
Launched20192022
Acquired byIBM (2024)CNCF sandbox
Cost allocationAny K8s conceptAny K8s concept
Multi-cluster✅ Yes✅ Yes
Cloud integrationAWS, Azure, GCPAWS, Azure, GCP
PricingFreemium + EnterpriseFree
Best forEnterprise cost managementOpen-source cost visibility

What Cost Tools Provide

FeatureDescription
Cost allocationBy namespace, deployment, label, team
Real-time monitoringIn-cluster + cloud costs
Optimization recommendationsRightsizing, waste detection
Anomaly detectionAlert on spend spikes
Multi-clusterUnified 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

  1. Deploys VPA in recommendation mode for all workloads
  2. Provides a dashboard showing recommendations
  3. 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

CombinationSafe?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:

  1. HPA scales up → more replicas
  2. VPA sees lower per-pod usage → reduces requests
  3. HPA sees higher utilization → scales up more
  4. 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 CaseExample
DNS scalingCoreDNS replicas scale with nodes
Ingress scalingNGINX replicas scale with nodes
MonitoringPrometheus 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

#FailureSymptomRoot CauseFix
1PDB blocks scale-downNodes never removedPDB prevents evictionAdjust PDB
2HPA/VPA conflictUnstable replicasBoth scale on CPUSeparate metrics
3Inflated requestsCluster appears busyRequests >> usageVPA rightsizing
4Karpenter consolidation stormConstant node churnConsolidation too aggressiveTune consolidation policy
5Spot interruption cascadeMultiple pods evictedAll replicas on same spot poolDiversify, PDB
6HPA metric unavailableHPA doesn't scaleCustom metrics API downFix metrics adapter
7KEDA scaler misconfigurationScale to zero unexpectedlyWrong metric thresholdTune scaler
8Cluster Autoscaler slowPods Pending for minutes3-4 minute provisioningMigrate to Karpenter
9Cost anomalyUnexpected bill spikeRunaway workload, no limitsSet limits, alerts
10Bin-packing breaks HASingle node failure kills serviceOver-consolidationPod 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?

ComponentImpactSeverity
HPA downNo replica scaling; capacity fixedSEV-2
VPA downNo rightsizingSEV-3
KEDA downNo event-driven scalingSEV-2
Karpenter downNo node provisioningSEV-1
Cluster Autoscaler downNo node scalingSEV-1
Cost monitoring downNo visibilitySEV-3
PDB blocking scale-downWasted costSEV-3

Mitigation Strategies

StrategyImplementation
HA autoscalersMultiple replicas
FallbackOn-demand node groups
MonitoringAlerts on scaling events
Cost alertsBudget alerts
TestingChaos engineering for scaling

PART 4: CAPACITY PLANNING & COST MODELING

17. Cost Modeling and FinOps

The FinOps Lifecycle

PhaseActivities
InformCost visibility, allocation, showback
OptimizeRightsizing, spot, bin-packing
OperateGovernance, budgets, alerts

Cost Allocation Dimensions

DimensionExample
Namespaceteam-a, team-b
Labelapp=web, env=prod
Deploymentweb, api, db
Clusterprod-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

OptimizationTypical SavingsEffort
Rightsizing (VPA)20–40%Low
Spot instances60–90% on eligible workloadsMedium
Bin-packing20–30%Medium
Karpenter consolidation30–50%Medium
KEDA scale-to-zero50–80% on batchMedium
Combined50–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

TargetArchitecture
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

StrategyAvailabilityCost
On-demand onlyHighestHighest
Mixed spot + on-demandHighMedium
Spot onlyMediumLowest
Bin-packedLower (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

ModelDescriptionImpact
ShowbackShow teams their costsAwareness
ChargebackCharge teams for costsAccountability

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

FrameworkRequirement
SOC2Change management, monitoring
PCI-DSSAccess controls, audit logs
HIPAAAudit trails, access controls
FedRAMPFIPS 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

SeverityImpactResponse TimeEscalation
SEV-1Cost spike > 200% / autoscaling failure causing outage5 minOn-call + Platform + Management
SEV-2Cost spike 50-200% / PDB blocking scale-down15 minOn-call + Platform
SEV-3Cost anomaly / optimization opportunity1 hourOn-call
SEV-4Rightsizing recommendation4 hoursTicket

PART 8: INTERVIEW PREPARATION

35. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
HPAScales replicas based on metrics
VPAAdjusts resource requests/limits
KEDAEvent-driven autoscaling, scale to zero
Cluster AutoscalerNode scaling (3-4 min)
KarpenterNode provisioning (45-60s), consolidation
Spot instances60-90% discount, interruption risk
Bin-packingMostAllocated scoring
Node consolidationKarpenter, Descheduler
PDBCan block scale-down
KubecostCost monitoring (IBM)
OpenCostCost monitoring (CNCF)
GoldilocksVPA recommendations dashboard
Resource requestsScheduler uses these, not usage
QoSGuaranteed > Burstable > BestEffort
HPA behaviorScale up fast, scale down slow
VPA + HPA conflictNever both on CPU
Karpenter consolidation50% node reduction in production
Cost governanceVisibility → 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

PhaseActivitiesTools
ProvisioningCreate control plane, join nodes, install CNI/CSIkubeadm, Cluster API, managed services
OperationsMonitor, scale, back up, rotate certsPrometheus, Velero, cert-manager
UpgradesControl plane, then workers, then validationkubeadm, Cluster API
Disaster RecoveryRestore from etcd snapshot or Velero backupetcdctl, Velero
RetirementDrain nodes, delete cluster, clean up cloud resourceskubectl, 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

ComponentRule
kube-apiserver (HA)Newest and oldest instances must be within one minor version
kubeletMust not be newer than apiserver; may be up to three minor versions older
kube-proxyMust not be newer than apiserver; may be up to three minor versions older
kubectlWithin 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

StepCommand
Check current versionkubectl version --short
Check target versionkubeadm upgrade plan
Audit deprecated APIskubectl get --raw /metrics | grep apiserver_requested_deprecated_apis
Back up etcdetcdctl snapshot save
Check PDBskubectl get pdb -A
Verify node healthkubectl 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 SizeExpected Time
3 nodes30–60 minutes
10 nodes2–4 hours
50 nodes8–12 hours
100+ nodes1–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:

FlagPurpose
--ignore-daemonsetsSkip DaemonSet Pods (they can't be evicted)
--delete-emptydir-dataDelete Pods using emptyDir
--forceForce deletion of Pods not managed by controllers
--grace-periodOverride default grace period
--timeoutTimeout 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:

MistakeImpact
Never allow disruptionsAllowed to equal 0 in steady stateDrain stalls forever
Using PDBs for single-replica deploymentsDrain blocks
Scope PDB selector too broadlyUnexpected protection
Not setting PDBs at allService 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

  1. Stop the API server (move static pod manifests)
  2. Remove old etcd data from /var/lib/etcd
  3. Restore the snapshot with etcdutl snapshot restore
  4. Restore static pod manifests
  5. Restart kubelet
  6. 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

ComponentMethod
Kubernetes objectsAPI server export
Persistent volumesCSI snapshots or file-system backup
CRDsAPI server export
NamespacesSelective backup
SecretsEncrypted 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

PracticeWhy
Use schedules, not manual backupsConsistency
Set appropriate TTLCost control (7–30 days typical)
Verify backup contentCheck datauploads, not just Completed status
Test restores regularlyBackups without restores are useless
Store offsiteProtect against site failure
Encrypt backupsSecurity

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

OperationWhat It Does
CompactionRemoves old revisions from the logical keyspace
DefragmentationReclaims 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:

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

CertificateDefault Validity
kube-apiserver serving cert1 year
kube-apiserver client cert1 year
etcd serving cert1 year
etcd peer cert1 year
kubelet client cert1 year
kubelet serving cert1 year
CA certificate10 years

Rotation Methods

MethodDescription
kubeadmkubeadm certs renew all
Managed servicesAutomatic (EKS, AKS, GKE)
Rancherrke certificate rotate
ManualRegenerate 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

PracticeWhy
Rotate before expiryAvoid cluster outage
Plan a maintenance windowControl plane briefly unavailable
Back up certificatesRollback safety
Test in stagingVerify procedure
Automate with managed servicesReduce 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

LayerPurposeExamples
CoreCluster and Machine abstractionsCluster, Machine, MachineSet
InfrastructureCloud resource provisioningAWSCluster, VSphereCluster
BootstrapTurn machine into K8s nodeKubeadmConfig, TalosConfig
Control PlaneManage control planeKubeadmControlPlane

CAPI v1.12 (January 2026)

The v1.12 release introduced in-place updates and chained 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

StrengthWhy
ConsistencySame API across clouds
GitOps compatibilityYAML in version control
Automated upgradesCAPI sequences control plane upgrades
Multi-cloud37+ infrastructure providers

When to Use CAPI

ScenarioCAPI?
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

ComponentPurpose
Karmada Control PlaneCentral API, scheduler, controllers
Member ClustersWorkload clusters (push or pull mode)
ResourceBindingWorkload distribution decisions
PropagationPolicyWhere 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 CaseDescription
Hybrid cloudRun workloads across AWS, GCP, on-prem
Multi-regionDistribute workloads globally
AI/ML trainingSchedule across GPU clusters
Disaster recoveryActive-active multi-cluster

Fleet (Rancher)

Fleet is Rancher's multi-cluster management tool. It deploys applications across clusters with GitOps.

Comparison

ToolApproachCNCF Status
KarmadaCentral control plane, propagation policiesGraduated
FleetGitOps-driven, Rancher-nativeIncubating
Cluster APIDeclarative cluster provisioningProduction-ready
vClusterVirtual clustersCNCF 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 TypeExample
Kernel deadlocksHung tasks, soft lockups
Hardware failuresDisk errors, memory errors
Network problemsNIC down, packet loss
Resource pressureDisk, 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

MetricDefinitionDepends On
RTO (Recovery Time Objective)Maximum acceptable downtimeRecovery speed
RPO (Recovery Point Objective)Maximum acceptable data lossBackup frequency

The Four Recovery Layers

For a recovery to count, four layers must come back:

  1. Cluster infrastructure (nodes, networking)
  2. Cluster state (etcd / API objects)
  3. Persistent data (volumes)
  4. 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

StrategyRPORTOCost
Backup/RestoreHoursHours$
SnapshotMinutesMinutes$$
ReplicationSecondsMinutes$$$
Active-ActiveZeroZero$$$$

DR Testing

TestFrequency
Restore etcd snapshotMonthly
Restore from VeleroMonthly
Full cluster rebuildQuarterly
Multi-region failoverQuarterly

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

#FailureSymptomRoot CauseFix
1etcd quorum lostAPI server unresponsiveMultiple etcd nodes downRestore from snapshot
2Upgrade blocked by PDBDrain stallsPDB too strictAdjust PDB, add capacity
3Certificate expiredkubelet can't connectNo rotationRotate certificates
4Deprecated API removedWorkloads fail after upgradeNo pre-upgrade auditAudit with kubectl convert
5etcd disk fullAPI errors, NOSPACE alarmDB grew beyond quotaDefragment, increase quota
6Velero backup failureNo backup for DRMisconfigured storageFix backup location
7Node stuck drainingDrain never completesPods without controllersUse --force
8Version skew violationSubtle failuresComponents on incompatible versionsFollow skew policy
9Cluster API reconciliation loopCluster stuckProvider bugCheck CAPI logs
10Multi-cluster split brainInconsistent stateNetwork partitionKarmada 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?

ComponentImpactSeverity
etcd quorum lostCluster unmanageableSEV-1
All control planes downCluster unmanageableSEV-1
Certificate expiredCluster breaksSEV-1
Failed upgradePartial control planeSEV-1
Velero backup failedNo DR protectionSEV-2
PDB blocks drainUpgrade stallsSEV-2
Node drain stuckMaintenance blockedSEV-3

PART 4: CAPACITY PLANNING & COST MODELING

17. Upgrade Cost and Time Modeling

Upgrade Time by Cluster Size

NodesControl PlaneWorkersTotal
315 min15 min30 min
1020 min2 hours2.5 hours
5030 min8 hours8.5 hours
100+45 min16 hours17 hours

Upgrade Cost

Cost ComponentEstimate
Engineering time2–8 hours
Maintenance window2–12 hours
Rollback cost1–4 hours

18. Backup Storage Cost Modeling

etcd Snapshot Storage

Cluster SizeSnapshot SizeFrequencyMonthly Storage
Small50 MBDaily1.5 GB
Medium500 MBDaily15 GB
Large2 GBDaily60 GB

Velero Backup Storage

Data SizeBackup SizeRetentionMonthly Storage
10 GB5 GB (compressed)7 days35 GB
100 GB50 GB7 days350 GB
1 TB500 GB7 days3.5 TB

Cost Optimization

StrategySavings
Compression50%
Deduplication30–50%
Lifecycle policies40–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

TargetArchitecture
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

ToolApproach
KyvernoClusterPolicy, multi-cluster via Cluster API
OPA GatekeeperConstraintTemplates
KarmadaPropagationPolicy
FleetGitOps bundles

Cluster Baseline

BaselineDescription
SecurityRBAC, PSS, NetworkPolicy, audit logging
ObservabilityPrometheus, logging, tracing
BackupVelero, etcd snapshots
UpgradeVersion skew policy, upgrade window

22. Compliance & Security for Cluster Operations

FrameworkCluster Ops Requirement
PCI-DSSChange management, audit logs, encryption
HIPAAAudit trails, access controls
SOC2Change management, monitoring
FedRAMPFIPS 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

SeverityImpactResponse TimeEscalation
SEV-1etcd quorum lost / all control planes down5 minOn-call + Platform + Management
SEV-2Upgrade failure / certificate expired15 minOn-call + Platform
SEV-3PDB blocks drain / backup failed1 hourOn-call
SEV-4Capacity planning warning4 hoursTicket

PART 8: INTERVIEW PREPARATION

35. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
Version Skew3 minor versions for kubelet; 1 for apiserver HA
Upgrade SequenceControl plane first, then workers one by one
kubeadm upgradeplan → apply → node (workers)
CordonMark node unschedulable
DrainEvict pods, mark unschedulable
UncordonMake node schedulable
PDBProtect during voluntary disruptions
etcd Backupetcdctl snapshot save with certs
etcd Restoreetcdutl snapshot restore
etcd CompactionRemove old revisions
etcd DefragReclaim disk space
VeleroWorkload backup and restore
Certificate Rotationkubeadm certs renew all
Cluster APIDeclarative cluster provisioning
CAPI v1.12In-place updates, chained upgrades
KarmadaMulti-cluster orchestration (CNCF Graduated)
Node Problem DetectorDaemonSet for node health
RTO/RPORecovery Time / Point Objectives
Fleet ManagementManagement 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

AspectCPUGPU
GranularityMillicoresWhole devices (unless shared)
SharingNative (time-slicing by kernel)Requires explicit configuration
Cost$0.05–$0.50/core/hour$2–$30+/GPU/hour
IsolationProcess-levelDevice-level (unless MIG)
MemoryNot a resourceCritical 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

LayerPurposeTools
Device ExposureMake GPUs available to KubernetesNVIDIA Device Plugin, DRA
SchedulingPlace pods on GPU nodesDefault scheduler, KAI, Kueue
Sharing/IsolationMultiple workloads per GPUTime-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

ComponentPurpose
DriverNVIDIA kernel modules
Container ToolkitExposes GPUs to containers
Device PluginRegisters GPUs with kubelet
DCGM ExporterGPU metrics
MIG ManagerMIG partition management
Node Feature DiscoveryLabels 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:


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:

ConfigurationPurpose
TaintKeep non-GPU workloads off GPU nodes
LabelIdentify GPU type/model
Node selector/affinityTarget 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

LimitationImpact
Integer-onlyNo fractional GPUs
No topology awarenessScheduler doesn't know NVLink
No attribute-based schedulingCan't request GPU with >40GB VRAM
No sharingUnless 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

AspectTime-SlicingMPSMIG
MechanismSoftware (CUDA context switching)Software (CUDA concurrency)Hardware (GPU partitioning)
Isolation❌ None⚠️ Limited✅ Full (dedicated SM + memory)
GPU SupportMost NVIDIA GPUsMost NVIDIA GPUsA100, A30, H100, H200+
Memory Isolation❌ No❌ No✅ Yes
Fault Isolation❌ No❌ No✅ Yes
ConfigurationSimpleMediumComplex
Best ForDev, non-criticalTrusted CUDAProduction, 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.

GPUMax MIG Instances
A100 (40GB)7
A100 (80GB)7
H100 (80GB)7
H2007

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:

MIG Profiles

ProfileSMsMemoryUse Case
1g.5gb1/75 GBSmall inference
2g.10gb2/710 GBMedium inference
3g.20gb3/720 GBLarge inference
4g.20gb4/720 GBTraining
7g.40gb7/740 GBFull 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

BenefitImpact
Hardware isolationNo noisy neighbors
Fault isolationOne instance crash doesn't affect others
Memory guaranteesDedicated VRAM per instance
Predictable performanceQoS guaranteed

MIG Limitations

LimitationImpact
GPU supportOnly A100, A30, H100, H200+
Static profilesMust be pre-configured
No dynamic reconfigurationRequires GPU reset
ComplexityMore 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.

ConnectionBandwidth
PCIe Gen5 x16128 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
SchedulerTopology 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 PluginDRA
Integer counts onlyAttribute-based requests
No topology awarenessTopology-aware
No sharing semanticsNative sharing support
Vendor-specificStandard API

DRA Concepts

ConceptPurpose
DeviceClassDescribes device capabilities
ResourceSliceRepresents allocatable capacity
ResourceClaimDeclarative workload request
ResourceClaimTemplateTemplate 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:

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:

FeatureStatusPurpose
Prioritized listStableFallback preferences (H100 → A100)
Extended resource supportBetaGradual migration from device plugin
Partitionable devicesBetaMIG-like partitioning via DRA
Device taintsBetaTaint faulty/reserved devices
Device binding conditionsBetaDelay 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

MetricMeaning
DCGM_FI_DEV_GPU_UTILGPU utilization %
DCGM_FI_DEV_MEM_COPY_UTILMemory bandwidth utilization
DCGM_FI_DEV_FB_USEDFramebuffer memory used (VRAM)
DCGM_FI_DEV_GPU_TEMPGPU temperature
DCGM_FI_DEV_POWER_USAGEPower consumption (watts)
DCGM_FI_DEV_XID_ERRORSGPU 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

AlertConditionAction
GPU IdleDCGM_FI_DEV_GPU_UTIL < 5% for 30 minKill idle workload
GPU Memory PressureDCGM_FI_DEV_FB_USED > 90%Increase GPU memory or MIG slice
GPU TemperatureDCGM_FI_DEV_GPU_TEMP > 85°CCheck cooling, throttle
GPU ErrorsDCGM_FI_DEV_XID_ERRORS > 0Investigate hardware

GPU Utilization Dashboard

Grafana dashboards for GPU monitoring show:


9. GPU Multi-Tenancy Strategies

The Four Layers of GPU Isolation

LayerMechanismIsolation Level
KubernetesNamespaces, RBAC, ResourceQuotaLogical
SchedulingPriorityClasses, node affinityPlacement
HardwareMIG, time-slicingPhysical/Logical
RuntimeKata 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:

TenantMIG ProfileGuaranteed Resources
Team A2g.10gb2/7 SMs, 10 GB VRAM
Team B2g.10gb2/7 SMs, 10 GB VRAM
Team C3g.20gb3/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:

Multi-Tenancy Decision Matrix

Tenant TypeIsolation Strategy
Internal teamsNamespaces + quotas + MIG
External customersvCluster + MIG + Kata
Regulated workloadsKata + MIG + dedicated nodes
Hostile tenantsSeparate 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

CapabilityPurpose
Gang schedulingAll-or-nothing placement for distributed jobs
Hierarchical queuesTeam quotas with DRF
Sub-GPU allocationFractional GPU support
Pre-scheduling simulationReduce preemption overhead
Fair sharingPrevent team starvation

When to Use KAI Scheduler

Use CaseKAI 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:

Kueue vs Volcano

AspectKueueVolcano
FocusJob queueingFull batch scheduler
Gang scheduling✅✅
Fair sharing✅✅
Topology awarenessLimited✅
CNCF StatusIncubatingIncubating

12. GPU Cost Optimization

The Five Strategies

StrategySavingsBest For
Spot instances70–91%Fault-tolerant training
Right-sizing GPU30–50%All workloads
MIG/time-slicing50–70%Inference
AutoscalingVariableInference
Reserved instances30–60%Predictable baseline

Training vs Inference Cost Profiles

AspectTrainingInference
PatternBatch, predictableContinuous, variable
DurationHours to days24/7
OptimizationSpot + checkpointingAutoscaling + sharing
CommitmentReserved instancesBaseline 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 SizeRecommended GPUVRAM
7B paramsA100 40GB16 GB (FP16)
13B paramsA100 40GB26 GB (FP16)
70B paramsA100 80GB / H100140 GB (FP16)
Fine-tuning 7BA100 40GB20 GB

Cost Per Token Optimization

For inference, the optimization goal is cost per token:

StrategyImpact
Mix GPU generationsH100 for prefill, A100 for decode
MIG for small modelsShare GPU across models
Autoscale on trafficScale to zero when idle
KV-cache optimizationReduce 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

ScenarioKata?
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

#FailureSymptomRoot CauseFix
1GPU not detectedPod Pending, no GPU resourceDriver issueCheck GPU Operator logs
2MIG configuration failedGPU reset errorActive processes on GPUStop all GPU workloads
3Time-slicing not workingOnly 1 pod per GPUConfigMap not appliedUpdate GPU Operator
4GPU OOMCUDA out of memoryVRAM exceededReduce batch size, use MIG
5GPU XID errorsWorkload crashesHardware/driver faultCheck DCGM metrics
6Noisy neighborUnpredictable latencyNo isolation (time-slicing)Use MIG
7GPU quota exceededPod PendingResourceQuota limitIncrease quota
8Cost anomalyUnexpected bill spikeIdle GPUs runningMonitor utilization
9MIG profile mismatchPod can't scheduleWrong MIG profile requestedCheck node MIG config
10NVLink topology ignoredSlow multi-GPU trainingDefault scheduler not topology-awareUse 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?

ComponentImpactSeverity
GPU Operator downNew GPUs not detectedSEV-1
Device plugin downGPU pods can't scheduleSEV-1
MIG misconfigurationGPU reset required, workloads killedSEV-1
GPU hardware failureNode unavailableSEV-1
Time-slicing without isolationNoisy neighborSEV-2
GPU quota exceededPods PendingSEV-3
Cost anomalyBudget overrunSEV-3

Mitigation Strategies

StrategyImplementation
HA GPU OperatorMultiple replicas
GPU node poolsDedicated nodes, taints
MIG for isolationHardware-level partitions
DCGM monitoringAlerts on GPU health
Cost alertsBudget-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

MetricTargetAction 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)

GPUCloud On-DemandSpotReserved
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

StrategySavings
Spot instances for training70–91% on eligible
MIG for inference50–70%
Right-size GPU type30–50%
AutoscalingVariable
Combined60%+

Cost Allocation

DimensionExample
Namespaceteam-a, team-b
Labelgpu-type=h100
MIG instance1g.5gb
Training jobexperiment-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

TargetArchitecture
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

ComponentPurpose
GPU OperatorDriver, device plugin, DCGM
Node Feature DiscoveryLabel GPU model
KarpenterGPU node provisioning
KAI SchedulerAI-aware scheduling
DCGMGPU monitoring
KubecostGPU cost allocation

22. Compliance & Security for GPU Workloads

FrameworkGPU Requirement
PCI-DSSIsolated GPU (MIG), audit logs
HIPAAEncrypted data, audit trails
SOC2Change management, monitoring
FedRAMPFIPS 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

SeverityImpactResponse TimeEscalation
SEV-1All GPU nodes down / GPU Operator failure5 minOn-call + Platform + ML Team
SEV-2Single GPU node failure / MIG corruption15 minOn-call + Platform
SEV-3GPU performance degradation1 hourOn-call
SEV-4GPU cost anomaly4 hoursTicket

PART 8: INTERVIEW PREPARATION

35. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
NVIDIA Device PluginExposes GPUs as nvidia.com/gpu
GPU OperatorManages drivers, plugin, DCGM
Time-SlicingSoftware sharing, no isolation
MPSCUDA concurrency, limited isolation
MIGHardware partitioning, full isolation
MIG Profiles1g.5gb, 2g.10gb, 3g.20gb, 7g.40gb
NVLink/NVSwitchHigh-speed GPU interconnect
Topology-AwareKubeNexus, HAMi, KAI Scheduler
DRADynamic Resource Allocation (future)
DCGMGPU monitoring (utilization, temp, errors)
GPU Multi-TenancyNamespaces + MIG + quotas + Kata
KAI SchedulerGang scheduling, fair share (CNCF Sandbox)
KueueJob queueing with quotas
VolcanoBatch/AI scheduling
Spot Instances70–91% savings for training
Cost OptimizationSpot + MIG + right-sizing + autoscaling
Kata ContainersVM-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

FailureWhat HappensImpact
Individual Pod PlacementDistributed training pods scheduled one by onePartial placement wastes GPUs while workers wait for peers
No Gang Scheduling4 GPUs available, 16-worker job needs 164 workers start, hold GPUs, wait forever for 12 more
No Team FairnessOne team's jobs starve another'sNo 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:

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

ToolApproachCNCF Status
VolcanoFull batch scheduling ecosystemIncubating
KAI SchedulerNVIDIA AI-aware schedulerSandbox
KueueAdmission + gang via integrationIncubating
CoschedulingScheduler pluginKubernetes 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

LayerResponsibilityTool
AdmissionShould this job run now?Kueue
PlacementWhich node should this pod go to?kube-scheduler / Volcano / KAI

Kueue decides when a job runs, not where its pods land.

Kueue Resources

ResourceScopePurpose
ResourceFlavorClusterDefines available resource types
ClusterQueueClusterDefines quota pool
LocalQueueNamespaceSubmission entry point
WorkloadNamespaceRepresents a job's resource needs
CohortClusterGroups 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

ScenarioKueue?
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

ComponentPurpose
Volcano SchedulerGang scheduling, fair-share, topology
Volcano ControllerJob lifecycle management
PodGroupGroup of pods scheduled together
QueueResource pool with quota

Volcano vs Kueue

AspectVolcanoKueue
Primary roleBatch schedulingAdmission control
Gang scheduling✅ Native✅ Via integration
Queue modelVolcano QueueClusterQueue + LocalQueue
Job controllerVolcano Job (vcjob)Kubernetes Job
CNCF StatusIncubatingIncubating

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

ScenarioVolcano?
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

FlagPurpose
--tensor-parallel-sizeNumber of GPUs for tensor parallelism
--max-model-lenMaximum sequence length
--gpu-memory-utilizationFraction of GPU memory to use (default 0.9)
--enable-prefix-cachingEnable KV-cache prefix reuse
--quantizationQuantization 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

FeaturePurpose
Continuous batchingDynamic request grouping for better GPU utilization
Token streamingBetter UX for long responses
Tensor parallelismMulti-GPU model sharding
QuantizationReduce memory footprint
Flash AttentionFaster 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

PracticeWhy
Set --num-shard = GPU countPrevent OOMKill mid-request
Tune --max-batch-prefill-tokensControl prefill memory
Tune --max-batch-total-tokensControl total batch memory
Use A10 or newerTGI 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

AspectTGIvLLM
Backed byHugging FacevLLM project
Continuous batching✅✅
PagedAttention❌ (uses different memory management)✅
Tensor parallelism✅✅
Streaming✅✅
EcosystemHugging FaceOpenAI-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

ScenarioTriton?
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

ScenarioImpact
Cache hit10x cheaper, 50x faster
Cache missFull recomputation
Cache-blind routingScatters 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

ScenarioOffloading?
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

MetricMeaningUse
num_requests_waitingQueue depthScale up trigger
num_requests_runningActive requestsUtilization
inter_token_latencyTime between tokensSLO metric
time_to_first_tokenTTFTUser 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

ActionTime
Scale up~30–60 seconds
Scale down~5 minute cooldown

Knative vs KEDA

AspectKnativeKEDA
Scaling metricRequest concurrencyCustom metrics
Scale to zero✅ Yes✅ (with HTTP add-on)
Cold startHigherLower
SLO-driven❌✅
Best forServerless inferenceProduction 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:

PhaseTimeOptimization
T_capacityNode provisioningKarpenter, warm pools
T_schedulePod schedulingNode affinity
T_imageImage pullImage pre-warming
T_modelModel weight loadingLocal NVMe cache
T_runtimeRuntime initializationPre-built runtime
T_warmupGPU warmupWarm 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.

StrategyCold StartCost
No warm pool5 minLowest
1 warm replica<10 secMedium
Full warm pool<1 secHighest

Model Caching Strategies

StrategyCold StartCost
Hugging Face Hub5+ min$
Local NVMe cache30 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

ScenarioCache-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

CapabilityPurpose
Gang schedulingAll-or-nothing placement
Hierarchical queuesTeam quotas with DRF
GPU sharingFractional GPU support
Topology-aware placementNVLink/NVSwitch awareness
Workload priority and preemptionCritical 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 CaseKAI?
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

#FailureSymptomRoot CauseFix
1Distributed training deadlockAll pods PendingNo gang schedulingUse Volcano/KAI
2Cold start timeoutAutoscaling failsModel loading takes 5+ minModel caching, warm pool
3KV-cache miss stormHigh latency, low throughputCache-blind routingllm-d, Gateway API
4GPU OOMKillPod killed mid-requestModel + KV-cache exceeds VRAMReduce batch size, quantize
5KEDA metric unavailableAutoscaling stuckPrometheus scrape failureFix ServiceMonitor
6Model cache staleWrong model servedCache not invalidatedVersion cache keys
7Gang scheduling deadlockPods Pending foreverminMember > available GPUsReduce workers, add GPUs
8Queue starvationOne team monopolizes GPUNo fair-share policyKueue/KAI queues
9Tensor parallel mismatchOOMKill mid-requestnum-shard > GPU countMatch num-shard to GPUs
10Cache-aware routing misconfiguredNo cache hitsWrong routing policyTune 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?

ComponentImpactSeverity
Gang scheduling failureAll distributed training deadlockedSEV-1
Inference engine downAll LLM requests failSEV-1
KEDA downNo autoscaling, capacity fixedSEV-2
KV-cache routing failure10x latency, 10x costSEV-2
Model cache corruptionWrong model servedSEV-1
Queue starvationOne team blocks othersSEV-2
Cold start timeoutAutoscaling ineffectiveSEV-2

Mitigation Strategies

StrategyImplementation
Gang schedulingVolcano or KAI Scheduler
Model cachingLocal NVMe, warm pools
Cache-aware routingllm-d, Gateway API
KEDA autoscalingQueue-depth metrics
Queue fairnessKueue, KAI queues
GPU monitoringDCGM, Prometheus

PART 4: CAPACITY PLANNING & COST MODELING

16. GPU Utilization and Cost Modeling

GPU Utilization Targets

MetricTargetAction if Below
GPU utilization> 70%Rightsize, consolidate
KV-cache hit rate> 50%Cache-aware routing
Queue depth< 5Scale up
Batch sizeMaximizeTune 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

StrategySavings
vLLM vs naive2–24x throughput
Continuous batching2–4x
PagedAttention2–4x memory efficiency
KV-cache offloading30–50%
Cache-aware routing10x on cache hits
Quantization2x memory reduction

17. Cost Per Token Optimization

The Four Levers

LeverImpactEffort
Inference engine2–24xLow
Batching2–4xLow
KV-cache10x on hitsMedium
Hardware2–3xHigh

Real-World Results

CompanyResult
Stripe73% cost reduction with vLLM (50M daily calls, 1/3 fleet)
Google CloudTiered KV-cache extends effective cache size
Kubex80% 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

TargetArchitecture
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

StrategyCold StartSLA Impact
No caching5 min❌ Autoscaling fails
Local NVMe30 sec⚠️ Slow but works
Warm pool<10 sec✅ Acceptable
Always-on0 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 TypeIsolationTool
Internal teamsNamespaces + Kueue queuesKueue
External customersvCluster + MIGvCluster
RegulatedKata Containers + MIGKata
HostileSeparate 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

FrameworkAI Requirement
PCI-DSSIsolated GPU, audit logs
HIPAAEncrypted model/data, audit
SOC2Change management, monitoring
GDPRData residency
EU AI ActModel 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

SeverityImpactResponse TimeEscalation
SEV-1All training deadlocked / inference down5 minOn-call + Platform + ML Team
SEV-2Partial GPU waste / slow inference15 minOn-call + Platform
SEV-3Cold start slow / cache miss1 hourOn-call
SEV-4Cost anomaly4 hoursTicket

PART 8: INTERVIEW PREPARATION

34. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
Default K8sIndividual pod placement, no gang scheduling
Gang SchedulingAll-or-nothing pod placement
PodGroupGroup of pods scheduled together
KueueJob admission, quota, fair sharing
ClusterQueueQuota pool for Kueue
VolcanoBatch scheduling, gang, queue
KAI SchedulerAI-aware, GPU sharing, topology
vLLMPagedAttention, continuous batching
TGIHugging Face inference server
TritonMulti-framework inference server
PagedAttentionPer-token-block KV-cache
Continuous BatchingDynamic request batching
KV-CacheInvisible state, 10x on hit
LMCacheKV-cache offloading to CPU/SSD
KEDAEvent-driven autoscaling
Model CachingLocal NVMe for fast cold start
Warm PoolsPre-loaded model instances
llm-dCache-aware routing
Gateway API InferenceAI-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

DriverDescription
IsolationSeparate prod/staging/dev, separate teams, separate customers
ResilienceSurvive zone, region, or provider failures
ComplianceData residency (EU data stays in EU)
ScaleBeyond 1,000–5,000 nodes per cluster
CostOptimize by region or provider
AcquisitionIntegrating acquired companies with their clusters

The Hidden Costs

CostDescription
Operational overheadN clusters × (upgrades + monitoring + backup + cert rotation)
Observability fragmentationMetrics, logs, traces scattered
Policy driftClusters configured differently
Networking complexityCross-cluster service discovery
Security surfaceMore control planes to secure
Cost trackingHarder 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 OpsPlatform Engineering
Tickets for infrastructureSelf-service
Manual provisioningGolden paths
Per-team toolingStandardized platform
ReactiveProactive

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

LevelWhat You OwnTools
Level 1: Multi-ClusterCluster lifecycle, provisioningCluster API, Terraform
Level 2: Multi-TenancyTenant isolation within a clustervCluster, Capsule, namespaces
Level 3: Platform EngineeringDeveloper experience, self-serviceBackstage, Crossplane
Level 4: GovernancePolicy, compliance, costKyverno, 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

ScenariovCluster?
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

BenefitDescription
FastCreate virtual clusters in seconds
CheapNo additional nodes
IsolatedEach vCluster has own API server
Self-serviceDevelopers manage their own cluster
Version-skewDifferent vCluster versions on same host

vCluster Limitations

LimitationImpact
No node isolationPods run on shared nodes
CRD conflictsSame CRDs can't be installed twice
Host cluster dependencyvCluster fails if host fails
NetworkingCross-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:

CRDPurpose
TenantA tenant with assigned users, groups, and namespaces
TenantResourceQuotaQuota 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

ScenarioCapsule?
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

ResourcePurpose
ClusterDefines a cluster
MachineRepresents a node
MachineSetGroup of machines
MachineDeploymentDeclarative machine management
KubeadmControlPlaneControl plane management

When to Use CAPI

ScenarioCAPI?
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

ComponentPurpose
Karmada Control PlaneCentral API, scheduler, controllers
Member ClustersWorkload clusters (push or pull mode)
ResourceBindingWorkload distribution decisions
PropagationPolicyWhere workloads should run

Karmada Use Cases

Use CaseDescription
Hybrid cloudRun workloads across AWS, GCP, on-prem
Multi-regionDistribute workloads globally
AI/ML trainingSchedule across GPU clusters
Disaster recoveryActive-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

ComponentPurpose
Fleet ManagerCentral controller in management cluster
Fleet AgentRuns in each managed cluster
GitRepoGit repository to sync
BundleSet of resources to deploy

Fleet vs Argo CD vs Flux

AspectFleetArgo CDFlux
Multi-cluster✅ Native✅✅
GitOps✅✅✅
Rancher integration✅❌❌
UIRancherArgo UIWeave GitOps

8. Crossplane

Crossplane extends Kubernetes to manage cloud resources as CRDs. Instead of Terraform, you define cloud resources as Kubernetes objects.

Crossplane Architecture

ComponentPurpose
ProviderCloud provider integration (AWS, GCP, Azure)
CompositeResourceCustom resource combining multiple cloud resources
CompositionTemplate for composite resources
ClaimDeveloper-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

AspectCrossplaneTerraform
ModelKubernetes-nativeCLI-driven
StateIn KubernetesIn state file
Drift detectionContinuousOn 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

FeaturePurpose
Software CatalogAll services, ownership, metadata
Software TemplatesGolden paths for new services
TechDocsDocumentation as code
PluginsExtensible ecosystem

Backstage Plugins (2026)

PluginPurpose
KubernetesView cluster resources
Argo CDView deployments
CrossplaneManage cloud resources
KubecostView 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

PracticeWhy
One repo per clusterIsolation
Separate config reposTeam autonomy
Use overlaysEnvironment-specific config
Automated drift detectionDetect 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:

Comparison

ToolApproachCNCF Status
SubmarinerL3 tunnelsSandbox
Cilium Cluster MesheBPFGraduated
KarmadaService propagationGraduated

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

ToolApproach
GitOpsArgo CD/Flux syncs policies
KarmadaPropagationPolicy
FleetGitRepo

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

FeatureImpact
In-place updatesFaster, less disruptive
Chained upgradesCatch up multiple versions in one operation

PART 3: PRODUCTION FAILURE MODES

15. Top 10 Multi-Cluster & Platform Failures

#FailureSymptomRoot CauseFix
1vCluster stuckVirtual cluster unresponsiveHost cluster resource exhaustionCheck host resources
2Karmada propagation failureWorkload not deployedPropagationPolicy misconfiguredCheck policy
3CAPI reconciliation loopCluster stuckProvider bugCheck CAPI logs
4Crossplane resource conflictCloud resource not createdIAM permissionsCheck provider logs
5GitOps driftCluster differs from GitManual changesReconcile
6Multi-cluster observability gapMissing metricsPrometheus scrape failureCheck ServiceMonitor
7Policy drift across clustersInconsistent enforcementManual configurationCentral policy management
8Backstage catalog staleWrong service infoNot syncedCheck Backstage logs
9Cluster API upgrade failureUpgrade stuckVersion skewCheck CAPI logs
10Cost allocation failureCan't attribute costsMissing labelsEnforce 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?

ComponentImpactSeverity
Management cluster downCan't manage fleetSEV-1
Karmada downNo cross-cluster schedulingSEV-2
CAPI downNo cluster provisioningSEV-2
GitOps downNo deploymentsSEV-2
Observability downNo visibilitySEV-2
Single cluster downDepends on multi-cluster setupSEV-1 to SEV-3

PART 4: CAPACITY PLANNING & COST MODELING

18. Multi-Cluster Cost Modeling

Cost Components

ComponentCost
Control plane$70–$150/month per cluster (managed)
Worker nodes$0.10–$3/hour per node
NetworkingCross-cluster data transfer
ObservabilityStorage for metrics/logs
BackupS3/GCS storage

The Multi-Cluster Cost Trap

TrapImpact
Idle clustersDev clusters running 24/7
Duplicate observabilityN Prometheus instances
No shared servicesEach cluster has own logging, monitoring

19. Platform Team Sizing and ROI

Platform Team Size by Organization

Org SizePlatform Engineers
50 developers2–4
200 developers5–10
1,000 developers20–40

Platform ROI

MetricImprovement
Developer onboarding2 weeks → 2 days
Deployment frequency10x
Change failure rate50% reduction
Mean time to recovery70% 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

TargetArchitecture
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 PathTool
New serviceBackstage template
New databaseCrossplane claim
New environmentvCluster
New clusterCluster API

Self-Service Guardrails

GuardrailTool
Resource quotasResourceQuota
Policy enforcementKyverno/OPA
Image signingcosign + Kyverno
Network isolationNetworkPolicy

23. Compliance & Security for Multi-Cluster

FrameworkMulti-Cluster Requirement
PCI-DSSIsolated clusters, audit logs
HIPAAAudit trails, encryption
SOC2Change management, monitoring
GDPRData residency
FedRAMPFIPS 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

SeverityImpactResponse TimeEscalation
SEV-1Management cluster down / all clusters affected5 minOn-call + Platform + Management
SEV-2Propagation failure / GitOps down15 minOn-call + Platform
SEV-3Single cluster issue1 hourOn-call
SEV-4Configuration warning4 hoursTicket

PART 8: INTERVIEW PREPARATION

36. Junior-Level Questions

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

QuestionExpected 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

ConceptKey Takeaway
vClusterVirtual Kubernetes clusters, fast, cheap
CapsuleNamespace-as-a-Service multi-tenancy
Cluster APIDeclarative cluster provisioning
KarmadaMulti-cluster orchestration (CNCF Graduated)
FleetRancher's multi-cluster GitOps
CrossplaneCloud resources as K8s CRDs
BackstageInternal Developer Portal
Argo CDMulti-cluster GitOps
FluxMulti-cluster GitOps
SubmarinerCross-cluster networking
Cilium Cluster MesheBPF multi-cluster
ThanosGlobal Prometheus view
MimirLong-term metrics storage
LokiMulti-cluster logging
Ownership LevelsMulti-cluster → Multi-tenancy → Platform → Governance
CAPI v1.12In-place updates, chained upgrades
Golden PathsPre-approved templates
IDPInternal Developer Platform

Pillar 3 Complete: The Full Curriculum

You've now completed Pillar 3: Deep Kubernetes, Platform Engineering & Extensibility, covering:

StageTopic
1Kubernetes Fundamentals (Day 0/1)
2kubectl Mastery & Debugging
3Control Plane Internals
4Workloads & Lifecycle Deep Dive
5Scheduling Deep Dive
6RBAC, ServiceAccounts & Security
7Kubernetes Networking Deep Dive
8Storage Deep Dive
9Cluster Extensibility (CRDs, Controllers, Operators)
10Autoscaling & Cost Optimization
11Cluster Lifecycle & Operations
12GPU Orchestration & Multi-Tenancy
13AI/ML Workload Orchestration
14Multi-Cluster & Platform Engineering