---
description: Kubernetes patterns—resource requests/limits, security context, probes, rollout, HPA, PDB, NetworkPolicy. Declarative; HA and security by default.
alwaysApply: false
---

# Kubernetes Patterns

Guidelines for workloads on Kubernetes.

## Core Principles

1. **Declarative** - Desired state in Git; controllers reconcile.
2. **Resource Limits Always** - Every container has requests and limits.
3. **Security by Default** - Non-root, read-only rootfs where possible, no privilege escalation, drop ALL capabilities.
4. **High Availability** - Multiple replicas; spread across failure domains (topologySpreadConstraints or podAntiAffinity).

## Pod Spec Essentials

- **Labels**: app.kubernetes.io/name, component, part-of, managed-by; consistent for selectors and monitoring.
- **securityContext** (pod): runAsNonRoot: true, runAsUser/runAsGroup, fsGroup; (container): allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities.drop: [ALL].
- **resources**: requests and limits for cpu and memory; set so scheduler and eviction work correctly.
- **Probes**: liveness (restart if unhealthy), readiness (traffic only when ready). Use httpGet or exec; set initialDelaySeconds, periodSeconds, timeoutSeconds, failureThreshold. Avoid long preStop unless needed for drain.
- **lifecycle.preStop**: Optional sleep or graceful shutdown hook so load balancer drops connections before SIGTERM.
- **envFrom**: configMapRef and secretRef for config and secrets; never plaintext secrets in env.

## Deployments

- **replicas**: At least 2 for HA; use HPA for scaling.
- **strategy**: RollingUpdate with maxSurge/maxUnavailable.
- **PodDisruptionBudget**: minAvailable or maxUnavailable so voluntary disruptions don’t take down the app.

## Networking

- **NetworkPolicy**: Default deny; then allow ingress from ingress controller and monitoring; egress to DNS, DB, Redis, and external HTTPS as needed. Use podSelector and namespaceSelector.

## Helm

- **Structure**: Chart with values.yaml and environment-specific values files; templates for Deployment, Service, HPA, PDB, ServiceMonitor, NetworkPolicy. Use _helpers.tpl for shared labels.
- **Versioning**: Pin app version in values; use same versioning scheme as image tag.

## Definition of Done (Workload)

- [ ] Resources, security context, and probes set; PDB and HPA if needed.
- [ ] NetworkPolicy restricts traffic; no default open.
- [ ] Rollout and rollback tested.

## Common Pitfalls

- **No resource limits** - Leads to noisy neighbors and OOM; always set.
- **Liveness too aggressive** - Can cause unnecessary restarts; prefer readiness for temporary unavailability.
- **Missing PDB** - Node drains or cluster upgrades can take all replicas; set minAvailable/maxUnavailable.
