Kubernetes for Developers: Probes, Resources and Autoscaling
Derar SattoufUpdated DevOps & cloud

Most developers do not need to run Kubernetes. They need to ship to it without surprises. The surprises are remarkably consistent: a pod that restarts every few minutes because a liveness probe is too aggressive, a service that returns 503 for two seconds during every deploy, a container killed with exit code 137 at 3 a.m., an autoscaler that never scales because nobody set CPU requests, a rollout that takes down the old version before the new one is ready.
Avoiding all of them takes a small set of ideas. Kubernetes is a reconciliation engine: you declare desired state, and controllers keep nudging reality toward it. Pods are disposable, so anything that must survive goes elsewhere. Use a Deployment for stateless apps, a Service for a stable address, and Ingress or Gateway API for external HTTP. Config goes in ConfigMaps and sensitive values in Secrets, preferably synced from a vault.
Probes and resources decide most of your stability. Readiness decides whether you receive traffic, liveness decides whether you are restarted, and startup protects slow boots. Never point liveness at a dependency like the database. Always set memory requests equal to limits, set CPU requests, and be cautious with CPU limits because they cause throttling. Exit code 137 plus OOMKilled means the memory limit was hit.
HPA needs CPU or memory requests to work out its usage percentage. Use KEDA for queue depth or event-driven scaling, and VPA in recommendation mode to right-size. Graceful shutdown has three parts: stop receiving traffic (preStop delay), handle SIGTERM (finish in-flight work), and set terminationGracePeriodSeconds longer than both. Add a PodDisruptionBudget and topology spread constraints so node drains and zone failures do not take you down.
When something breaks, work in order: kubectl get, describe, logs --previous, events, then exec or an ephemeral debug container. Develop locally with kind or minikube plus Tilt or Skaffold, keep Helm or Kustomize for packaging, and control cost by right-sizing requests, not by guessing.
Kubernetes ships roughly three minor releases a year. As of late 2026 Kubernetes 1.37 is the newest minor release, with 1.36 and 1.35 still supported. In-place resize of container resources went GA in 1.35, and in-place resize for pod-level resources reached beta in 1.36. Anything else version-sensitive is marked "verify against current docs", so run kubectl version and check the release notes for the cluster you actually use. Hardening (non-root, seccomp, network policy, image scanning) is covered in container security hardening for Docker and Kubernetes, so this post doesn't repeat it.
The mental model
Five ideas explain most Kubernetes behavior.
1. Desired state and reconciliation. You submit objects (a Deployment saying "three replicas of this image"). Controllers continuously compare reality to that spec and make changes. If a pod dies, the ReplicaSet controller creates another. Nothing is "run once".
2. Pods are ephemeral and replaceable. A pod is one or more containers sharing a network namespace and volumes. It has its own IP, which changes whenever it is recreated. Never depend on a pod name or IP. Local disk inside a container vanishes on restart.
3. Labels and selectors are the glue. A Service finds pods by label. A Deployment owns pods by label. Most "it deploys but nothing receives traffic" bugs are a selector that does not match a label.
4. Everything is an API object. kubectl is just an HTTP client. YAML is a serialization of objects. You can kubectl explain deployment.spec.strategy to read the schema from the live cluster.
5. The scheduler places pods using requests. The scheduler does not look at what your pod uses; it looks at what it asked for (requests) and finds a node with that much unreserved capacity. Resource requests are therefore both a scheduling input and a cost input.
kubectl apply -f app.yaml
|
v
API server ----> etcd (stored desired state)
|
+--> Deployment controller --> ReplicaSet --> Pods (pending)
|
Scheduler: picks a node by requests, affinity, spread
|
kubelet on node: pulls image, starts containers,
runs probes, reports status
|
Service + EndpointSlices: only Ready pods get trafficVocabulary cheat sheet
| Term | Meaning | Developer relevance |
|---|---|---|
| Pod | Smallest deployable unit; one or more containers | Your app runs here |
| ReplicaSet | Keeps N pods running | You rarely touch it directly |
| Deployment | Manages ReplicaSets and rolling updates | Your default workload type |
| StatefulSet | Stable identity and storage per replica | Databases, brokers; avoid for app code |
| Job and CronJob | Run to completion, scheduled | Migrations, batch |
| DaemonSet | One pod per node | Agents, log shippers |
| Service | Stable virtual IP and DNS name for pods | How other pods call you |
| Ingress and Gateway API | External HTTP routing | How users call you |
| Namespace | Scope for names, quotas, and RBAC | Environment or team boundary |
| ConfigMap and Secret | Configuration and sensitive data | Env vars and mounted files |
| Node | A machine running pods | Usually someone else's problem |
The objects you touch every day
Deployment
This is the baseline manifest. Every field here is deliberate; later sections explain why.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
labels:
app.kubernetes.io/name: orders-api
spec:
replicas: 3
revisionHistoryLimit: 5
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
selector:
matchLabels:
app.kubernetes.io/name: orders-api
template:
metadata:
labels:
app.kubernetes.io/name: orders-api
spec:
terminationGracePeriodSeconds: 45
containers:
- name: api
image: ghcr.io/example/orders-api:2.7.1
ports:
- name: http
containerPort: 8080
env:
- name: APP_ENV
value: production
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: orders-api-secrets
key: DATABASE_URL
envFrom:
- configMapRef:
name: orders-api-config
resources:
requests:
cpu: 250m
memory: 384Mi
limits:
memory: 384Mi
startupProbe:
httpGet: { path: /livez, port: http }
periodSeconds: 3
failureThreshold: 30
readinessProbe:
httpGet: { path: /readyz, port: http }
periodSeconds: 5
failureThreshold: 2
livenessProbe:
httpGet: { path: /livez, port: http }
periodSeconds: 10
failureThreshold: 3
lifecycle:
preStop:
exec:
command: ["sleep", "10"]Service
apiVersion: v1
kind: Service
metadata:
name: orders-api
spec:
selector:
app.kubernetes.io/name: orders-api
ports:
- name: http
port: 80
targetPort: httpInside the cluster, other pods reach you at orders-api (same namespace) or orders-api.prod.svc.cluster.local. Service types: ClusterIP (default, internal), NodePort (rarely what you want), LoadBalancer (provisions a cloud load balancer; each one costs money, so prefer one shared ingress or gateway), and ExternalName (DNS alias).
Ingress vs Gateway API
Ingress is the older, simpler API for HTTP routing. Gateway API is the newer, role-oriented, more expressive successor (GatewayClass, Gateway, HTTPRoute, and more), and it is where the ecosystem investment is going. Note that the Kubernetes project announced the retirement of the widely used ingress-nginx controller in 2026; if you depend on it, read the current announcement and plan a migration to a supported Gateway API implementation or another maintained ingress controller. Verify the timeline against current docs.
| Ingress | Gateway API | |
|---|---|---|
| Maturity | Stable, frozen feature set | GA core resources (v1), growing extension set |
| Routing features | Host and path; the rest via vendor annotations | Header and query matching, weights, redirects, rewrites as first-class fields |
| Ownership model | One object mixes platform and app concerns | Platform owns Gateway, app teams own HTTPRoute |
| Portability | Annotations differ per controller | Standardized fields, fewer annotations |
| Use when | Existing clusters, simple needs | New builds, canary and header routing, multi-team clusters |
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: orders-api
spec:
parentRefs:
- name: public-gateway
namespace: infra
hostnames:
- api.example.com
rules:
- matches:
- path:
type: PathPrefix
value: /orders
backendRefs:
- name: orders-api
port: 80ConfigMaps and Secrets
Use a ConfigMap for non-sensitive settings and a Secret for sensitive ones. Two behaviors surprise people. First, environment variables are read at container start: changing a ConfigMap does not change a running pod's environment. Mounted files do update eventually (not instantly, and not for subPath mounts), but most apps read config only at boot. The common fix is to roll the Deployment on config change, which Helm achieves with a checksum annotation and Kustomize achieves by generating ConfigMaps with a content hash suffix. Second, Secrets are base64 encoded, not encrypted; enable encryption at rest on the cluster, restrict who can read them, and prefer syncing from a vault with External Secrets Operator or your cloud's CSI driver. See the GitOps companion post on secrets models.
apiVersion: v1
kind: ConfigMap
metadata:
name: orders-api-config
data:
LOG_LEVEL: info
FEATURE_NEW_CHECKOUT: "false"Remember that ConfigMap and Secret values must be strings, so quote booleans and numbers.
Namespaces, quotas and defaults
Use namespaces as environment or team boundaries. Platform teams usually attach a ResourceQuota (total CPU, memory, object counts) and a LimitRange (defaults and maximums per container). If you omit resources, a LimitRange may inject defaults you did not choose; check with kubectl get limitrange -n <ns> -o yaml.
Probes done right
Probes are the thing most worth getting right. Bad probes cause more self-inflicted outages than almost anything else.
The three probes
| Probe | Question it answers | On failure | Typical endpoint |
|---|---|---|---|
| Startup | Has the app finished booting? | Keep waiting; after the failure threshold, restart the container. Disables liveness and readiness until it succeeds | The same as liveness |
| Readiness | Should this pod receive traffic right now? | Remove from Service endpoints (no restart) | Checks the app can serve: warm caches loaded, critical local state ready |
| Liveness | Is this process wedged beyond recovery? | Kill and restart the container | A trivial check that the event loop responds |
Rules that prevent outages
- Liveness must not check dependencies. If liveness calls the database and the database blips, every pod fails liveness simultaneously, all restart, and you turn a brief dependency issue into a full outage plus a thundering herd on recovery. Liveness answers only "is my own process alive and not deadlocked".
- Readiness may check dependencies the pod truly cannot work without, but think twice. If readiness depends on a shared database, a database blip drains every pod from the Service and you serve 503s for everything, including requests that do not need the database. Often a better design is to stay ready, fail individual requests with a clear error, and use a circuit breaker. If you do check dependencies, keep the check cheap and cache its result for a few seconds.
- Use a startup probe for slow boots instead of a huge
initialDelaySecondson liveness. A startup probe withperiodSeconds: 3andfailureThreshold: 30gives 90 seconds to boot, but a fast boot succeeds immediately and probing switches to the tighter intervals. - Make timeouts realistic. The default
timeoutSecondsis 1. A garbage collection pause, a CPU throttle, or a cold JIT can exceed it. Raise it to 2 or 3 for JVM, Node under load, or CPU-limited pods. - Be conservative with liveness
failureThreshold. Three consecutive failures at a 10 second period is 30 seconds of unresponsiveness before a restart; that is usually right. Aggressive liveness is the classic cause of restart storms under load, because a busy pod fails its probe, is killed, and moves its load to the remaining pods. - Distinguish
/livezfrom/readyz. They are different questions; do not point both at/health. - Probe a port the app owns, not through the Service. Probes run against the pod IP from the kubelet.
- Return quickly and cheaply. A probe that allocates, logs, and hits three downstreams adds load precisely when load is highest.
Probe handler types
| Type | Use when | Watch out for |
|---|---|---|
httpGet | HTTP services (default choice) | Any status 200 to 399 passes |
tcpSocket | Non-HTTP servers | Only proves the port is open |
grpc | gRPC services implementing the gRPC health protocol | Requires the standard health service |
exec | Scripts, legacy | Spawns a process per probe; heavier, and timeouts are enforced |
A worked example: a Node.js health endpoint
import http from "node:http";
let ready = false;
let shuttingDown = false;
const server = http.createServer((req, res) => {
if (req.url === "/livez") {
// Only checks that the event loop can answer.
res.writeHead(200).end("ok");
return;
}
if (req.url === "/readyz") {
const ok = ready && !shuttingDown;
res.writeHead(ok ? 200 : 503).end(ok ? "ready" : "not ready");
return;
}
// ... real routes
res.writeHead(404).end();
});
async function warmUp() {
await loadReferenceData(); // e.g. feature flags, small caches
ready = true;
}
server.listen(8080, () => warmUp().catch((e) => { console.error(e); process.exit(1); }));
declare function loadReferenceData(): Promise<void>;Notice shuttingDown: readiness flips to false as soon as the app receives SIGTERM, which helps drain traffic quickly (more in the graceful shutdown section).
Common probe failure patterns
| Symptom | Likely cause | Fix |
|---|---|---|
| Restarts roughly every few minutes under load | Liveness timeout too tight, or CPU throttling delays response | Raise timeoutSeconds, add CPU requests, relax thresholds |
| Pod never becomes Ready, no restarts | Readiness endpoint failing, or wrong port or path | kubectl describe pod, check probe events; kubectl port-forward and curl |
| Restart loop right after start | Liveness begins before boot completes | Add a startup probe |
| All pods restart together | Liveness checks a shared dependency | Remove dependency checks from liveness |
Readiness probe failed: connection refused at boot | App binds to 127.0.0.1 | Bind to 0.0.0.0 |
Requests, limits, and QoS
Resource settings are where application developers most often guess, and where the platform punishes guesses.
Definitions
- Request: the amount the scheduler reserves for your container. It is also the denominator HPA uses for its usage percentage and, on most platforms, what you are billed for indirectly (the node count follows total requests).
- Limit: a hard cap enforced at runtime. For memory, exceeding the limit means the kernel OOM-kills your process. For CPU, exceeding the limit means throttling.
CPU is measured in cores (1 equals one vCPU; 250m is a quarter). Memory is bytes with suffixes: Mi and Gi are powers of two, M and G are powers of ten. Mixing them up is a classic typo.
Quality of Service classes
Kubernetes derives a QoS class from your settings. It determines eviction order under node memory pressure.
| QoS class | How you get it | Eviction priority |
|---|---|---|
| Guaranteed | Every container has CPU and memory requests equal to limits | Last to be evicted |
| Burstable | At least one request or limit set, but not Guaranteed | Middle; evicted based on how much usage exceeds requests |
| BestEffort | No requests or limits at all | First to be evicted |
A sensible default policy
resources:
requests:
cpu: 250m
memory: 384Mi
limits:
memory: 384MiThat is: memory request equals memory limit, CPU request set, no CPU limit. The reasoning:
- Memory is incompressible. If a pod uses more than it requested and the node runs short, it may be evicted. Setting request equal to limit makes memory use predictable and avoids surprising evictions.
- CPU is compressible. A CPU limit throttles you even when the node has idle cores, which creates latency spikes. A CPU request guarantees you a proportional share when the node is busy and lets you burst when it is not.
- There is a legitimate counter-argument for CPU limits: in multi-tenant clusters with noisy neighbors or when you need predictable performance for benchmarks and cost allocation, limits provide a ceiling. If your platform team requires CPU limits, set them generously (two to four times the request), and watch throttling metrics.
CPU throttling in detail
CPU limits are enforced by the Linux CFS bandwidth controller in periods of 100 ms by default. A container with a limit of 500m may use 50 ms of CPU time per 100 ms period. A multithreaded app can burn its 50 ms in the first 10 ms across several threads, then be paused for the remaining 90 ms, even though the average is under the limit. The user-visible effect is latency spikes and failing probes.
Check throttling with the cgroup statistics inside the container or with the standard metric container_cpu_cfs_throttled_periods_total divided by container_cpu_cfs_periods_total:
# cgroup v2 path inside the container
kubectl exec deploy/orders-api -- cat /sys/fs/cgroup/cpu.stat
# look at nr_throttled and throttled_usecA throttled ratio consistently above a few percent on a latency-sensitive service is a sign to raise or remove the CPU limit.
Runtime defaults also interact: Go sets GOMAXPROCS from the number of host cores unless told otherwise (recent Go versions are container-aware, check your toolchain version); the JVM sizes thread pools and GC from detected CPUs; Node.js worker pools are fixed unless you configure them. Make sure your runtime sees the CPU you actually have.
Memory: OOMKilled and exit code 137
When a container exceeds its memory limit, the kernel kills it. You will see this:
kubectl get pod orders-api-7d9f8b6c5-abcde -o jsonpath='{.status.containerStatuses[0].lastState.terminated}'
# {"exitCode":137,"reason":"OOMKilled", ...}Exit code 137 is 128 plus signal 9 (SIGKILL). It means something killed the process with no chance to clean up; OOM is the most common cause, but a failed termination grace period also yields 137.
Causes and fixes:
| Cause | Fix |
|---|---|
| Limit simply too low for the working set | Measure peak usage (kubectl top pod, dashboards), set request and limit to peak plus 20 to 30 percent headroom |
| JVM heap set larger than the container limit | Use -XX:MaxRAMPercentage=70 (or similar) so heap tracks the container limit; remember metaspace and thread stacks live outside the heap |
| Node.js heap default too low or too high | Set --max-old-space-size to roughly 75 percent of the limit (in MiB) |
| Memory leak | Profile; a leak will eventually hit any limit. Use heap snapshots, pprof, or your runtime's profiler |
| Page cache or tmpfs counted | emptyDir with medium: Memory and file caches count toward the limit |
| Spiky workloads (large uploads, big JSON) | Stream instead of buffering; cap request sizes |
An important diagnostic distinction: OOMKilled in lastState.terminated.reason means the container exceeded its own limit. Pod status Evicted with a message about node memory pressure means the node ran out, which points at requests set too low across many pods.
In-place resize
Kubernetes 1.35 made in-place resizing of container CPU and memory GA: you can change a running pod's resources without recreating it, for example through the resize subresource, and the container may or may not restart depending on its resizePolicy. This is useful for VPA's in-place mode and for vertical scaling of stateful workloads. Behavior and flags are version dependent, so verify against the current docs for your cluster version.
Finding the right numbers
- Deploy with generous values in a staging environment.
- Run a realistic load test that includes peak traffic shapes.
- Record p95 CPU and p99 memory per pod from metrics.
- Set CPU request near p90 to p95 of observed CPU; set memory request and limit to peak plus headroom.
- Run the Vertical Pod Autoscaler in recommendation mode (
updateMode: "Off") for a week of production data and compare. - Revisit after any significant release.
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: orders-api
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: orders-api
updatePolicy:
updateMode: "Off" # recommend onlykubectl describe vpa orders-api
# Look at "Recommendation: Target / Lower Bound / Upper Bound" per containerVPA is a separately installed add-on, not part of core Kubernetes. Do not combine VPA auto mode with an HPA that scales on the same CPU or memory metric; they fight.
Autoscaling: HPA, VPA, KEDA
Horizontal Pod Autoscaler
HPA adjusts replica counts based on metrics. The core formula is:
desiredReplicas = ceil( currentReplicas * currentMetricValue / targetMetricValue )For CPU, "value" is the average of (usage divided by request) across pods. This is why CPU requests are mandatory for CPU-based HPA: with no request, there is no percentage to compute and the HPA reports <unknown>.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: orders-api
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: orders-api
minReplicas: 3
maxReplicas: 30
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 65
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 30
- type: Pods
value: 4
periodSeconds: 30
selectPolicy: Max
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 20
periodSeconds: 60Design notes:
- Target 60 to 70 percent CPU usage so there is headroom while new pods start. Targeting 90 percent means you are already saturated by the time replicas arrive.
- Scale up fast, scale down slowly. The
behaviorblock above allows doubling every 30 seconds up, and removes at most 20 percent per minute after a five minute stabilization window. - Pod startup time sets your reaction time: image pull, boot, and readiness. Smaller images, pre-pulled images on nodes, and fast startups directly improve autoscaling.
- HPA reacts to averages. A single hot pod will not trigger scaling; investigate load balancing (HTTP/2 and gRPC long-lived connections pin to pods behind a ClusterIP Service).
- HPA on memory is rarely helpful because most runtimes do not release memory when load drops, so it scales up and never down.
- Combine HPA with the node autoscaler (Cluster Autoscaler or Karpenter on supporting platforms). HPA creates pending pods; the node autoscaler adds nodes for them.
- HPA scale-to-zero (the
HPAScaleToZerofeature gate) was alpha for years. Kubernetes 1.37 moved it to beta and enabled it by default (release post), so on 1.36 and earlier you need to enable the gate yourself. Consider KEDA for scale-to-zero today.
Custom and external metrics
HPA can scale on per-pod custom metrics (for example requests per second) or external metrics (for example queue depth) if a metrics adapter exposes them (Prometheus Adapter, or KEDA, which provides an adapter). Scaling on a business-relevant signal beats CPU for I/O-bound services.
KEDA: event driven autoscaling
KEDA (Kubernetes Event-driven Autoscaling) is a CNCF graduated project that creates and manages an HPA for you based on many scalers: Kafka lag, RabbitMQ and SQS queue length, Prometheus queries, cron schedules, and more. It also supports scaling to and from zero.
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: orders-worker
spec:
scaleTargetRef:
name: orders-worker
minReplicaCount: 0
maxReplicaCount: 50
cooldownPeriod: 120
triggers:
- type: rabbitmq
metadata:
queueName: orders
mode: QueueLength
value: "100"
authenticationRef:
name: rabbitmq-authThe value here means "target about 100 messages per replica". Pair queue-based scaling with workers that are idempotent and shut down gracefully, because scale-in kills pods mid-work (see event-driven architecture with outbox and idempotency). Check the KEDA docs for the current scaler metadata keys, as they vary per scaler and change across versions.
Choosing a scaler
| Situation | Use |
|---|---|
| CPU-bound stateless web service | HPA on CPU usage |
| I/O-bound web service | HPA on requests per second or latency via custom metrics |
| Queue or stream consumers | KEDA on queue length or consumer lag |
| Scheduled load (business hours) | KEDA cron scaler or a scheduled scale of min replicas |
| Unknown right size | VPA in recommendation mode first |
| Need scale to zero | KEDA (or HPA scale-to-zero if enabled in your version) |
| Stateful single-writer workload | Vertical resize, not horizontal |
Autoscaling lab
- Deploy the Deployment with CPU requests set and the HPA above.
- Confirm the HPA can read metrics:
kubectl get hpa orders-apishould show a number, not<unknown>. If unknown, install metrics-server and verifykubectl top podsworks. - Generate load:
kubectl run load --rm -it --image=busybox -- /bin/sh -c "while true; do wget -q -O- http://orders-api/; done". - Watch:
kubectl get hpa orders-api -wandkubectl get pods -w. - Stop the load and observe the scale-down delay.
Rolling updates and rollouts
A Deployment's default RollingUpdate replaces pods gradually. Two parameters control it:
| Parameter | Meaning | Recommended |
|---|---|---|
maxSurge | Extra pods allowed above desired during rollout | 1, or 25 percent |
maxUnavailable | Pods allowed to be unavailable during rollout | 0 for user-facing services |
With maxUnavailable: 0 and maxSurge: 1, Kubernetes starts one new pod, waits for it to become Ready, then terminates one old pod. This only works safely if your readiness probe is accurate. A pod that reports Ready before it can serve will receive traffic and fail it.
Rollout commands you should know
kubectl rollout status deploy/orders-api --timeout=5m
kubectl rollout history deploy/orders-api
kubectl rollout undo deploy/orders-api # previous revision
kubectl rollout undo deploy/orders-api --to-revision=3
kubectl rollout restart deploy/orders-api # rolling restart, same spec
kubectl set image deploy/orders-api api=ghcr.io/example/orders-api:2.7.2
kubectl rollout pause deploy/orders-api # batch several edits
kubectl rollout resume deploy/orders-apiIf you use GitOps, prefer reverting the commit over rollout undo; otherwise the controller will reapply the bad version. See GitOps in practice with Argo CD and Flux.
Detecting a stuck rollout
Set progressDeadlineSeconds (default 600) and make your CI wait on kubectl rollout status, which returns non-zero if the deadline passes. A rollout stalls when new pods never become Ready: check kubectl describe on the new ReplicaSet's pods.
Beyond rolling updates
| Strategy | What it gives | Tooling |
|---|---|---|
| Rolling (default) | Gradual replacement, no extra tooling | Deployment |
| Recreate | Old pods all stop, then new start; downtime, but needed for singletons with exclusive state | Deployment strategy.type: Recreate |
| Blue-green | Two full environments, switch the Service or route | Argo Rollouts, manual Service selector flip |
| Canary | Gradual traffic shift with metric analysis | Argo Rollouts, Flagger, service mesh, Gateway API weights |
Gateway API supports weighted backends natively, which gives a basic canary without extra controllers:
rules:
- backendRefs:
- name: orders-api-stable
port: 80
weight: 95
- name: orders-api-canary
port: 80
weight: 5Database migrations and rolling updates
During a rolling update, old and new versions run simultaneously against the same database. Use expand and contract: first deploy a migration that only adds (new nullable column, new table), then deploy code that writes both and reads the new, then later remove the old column. Never ship a migration that breaks the previous code version, because rollback then becomes impossible. Run migrations as a Job or init step, not at application startup in every replica (racing migrations are a classic bug).
Graceful shutdown: no more 503s on deploy
During every deploy, scale-down, or node drain, Kubernetes terminates pods. If you handle this badly, clients see connection resets and 502 or 503 errors for a few seconds on every release.
What actually happens on termination
1. Pod marked Terminating; removed from Service endpoints (async)
2. preStop hook runs (if defined)
3. SIGTERM sent to PID 1 of each container
4. ... terminationGracePeriodSeconds countdown (default 30s) ...
5. SIGKILL if still runningThe subtle part is that steps 1 (endpoint removal) and 2 to 3 happen concurrently and asynchronously. Load balancers, ingress controllers, and kube-proxy need time to learn the pod is gone. If your process exits immediately on SIGTERM, requests already routed to it fail. The standard fix is to keep serving for a few seconds after SIGTERM, and to flip readiness to failing so you stop attracting new work.
The three-part recipe
- preStop sleep (5 to 15 seconds) to cover propagation delay. Newer Kubernetes versions support a native
sleepaction inlifecycle.preStop(check that it is available in your version), which also works with distroless images that lack asleepbinary. Theexecform needs a shell orsleepin the image. - Handle SIGTERM in the app: stop accepting new connections, finish in-flight requests, close pools, then exit.
- Set
terminationGracePeriodSecondsgreater than preStop plus your worst-case drain time. The preStop time counts against the grace period.
spec:
terminationGracePeriodSeconds: 45
containers:
- name: api
lifecycle:
preStop:
sleep:
seconds: 10Node.js example
import http from "node:http";
const server = http.createServer(handler);
let shuttingDown = false;
function handler(req: http.IncomingMessage, res: http.ServerResponse) {
if (req.url === "/readyz") {
res.writeHead(shuttingDown ? 503 : 200).end();
return;
}
if (shuttingDown) res.setHeader("Connection", "close");
res.writeHead(200).end("hello");
}
server.listen(8080);
async function shutdown(signal: string) {
if (shuttingDown) return;
shuttingDown = true;
console.log(`received ${signal}, draining`);
// Stop accepting new connections; in-flight requests finish.
server.close(async (err) => {
try {
await closeDatabasePool();
} finally {
process.exit(err ? 1 : 0);
}
});
// Safety net below terminationGracePeriodSeconds minus preStop.
setTimeout(() => process.exit(1), 25_000).unref();
}
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));
declare function closeDatabasePool(): Promise<void>;Go example
package main
import (
"context"
"log"
"net/http"
"os/signal"
"syscall"
"time"
)
func main() {
srv := &http.Server{Addr: ":8080", Handler: routes()}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}()
<-ctx.Done()
// preStop already delayed us; flip readiness elsewhere, then drain.
shutdownCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("forced shutdown: %v", err)
}
}
func routes() http.Handler { return http.NewServeMux() }The PID 1 trap
If your container runs a shell wrapper (CMD npm start, sh -c "node app.js"), SIGTERM may be delivered to the shell, which does not forward it, so your app never hears it and gets SIGKILLed after 30 seconds. Symptoms: every deploy takes exactly the grace period to terminate pods. Fixes: use exec-form CMD ["node", "dist/server.js"], exec node ... in shell scripts, or an init like tini (Docker's --init; in Kubernetes, shareProcessNamespace is a different thing, so add tini in the image). Also note that npm start itself may not forward signals; run node directly.
Long-lived connections
WebSockets, SSE, and gRPC streams are not drained by server.close() alone. Send a close frame or a goaway, give clients a reconnect hint, and let them reconnect to a healthy pod. Budget the grace period for the longest request you are willing to finish; beyond that, accept the cut.
PodDisruptionBudget
Voluntary disruptions (node drains for upgrades, cluster autoscaler scale-down) evict pods. A PodDisruptionBudget limits how many pods of an app can be down at once during them.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: orders-api
spec:
minAvailable: 2
selector:
matchLabels:
app.kubernetes.io/name: orders-apiPitfalls: a PDB with minAvailable equal to replicas (or maxUnavailable: 0) blocks node drains forever and your platform team will page you; with a single replica, a PDB of minAvailable: 1 blocks all drains. PDBs do not protect against involuntary failures (node crash) and do not apply to rolling updates (those are governed by maxUnavailable). Use unhealthyPodEvictionPolicy: AlwaysAllow (check availability in your version) so a stuck, never-Ready pod can still be evicted.
Spreading pods: topology and affinity
Three replicas on one node is not high availability. Use topology spread constraints to distribute across zones and nodes.
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app.kubernetes.io/name: orders-api
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app.kubernetes.io/name: orders-apiwhenUnsatisfiable: DoNotSchedule makes the constraint hard, which can leave pods Pending if a zone is full or down; ScheduleAnyway makes it a preference. For most apps, hard spread across zones is only worth it when you have enough capacity per zone.
| Mechanism | Use for |
|---|---|
| Topology spread constraints | Even distribution across zones and nodes (preferred modern approach) |
| Pod anti-affinity | "Not on the same node as pods labeled X", more verbose |
| Node affinity and nodeSelector | Place on specific hardware (GPU, arm64, spot) |
| Taints and tolerations | Reserve nodes for specific workloads |
| Priority classes | Which pods win under resource pressure |
Be aware that cross-zone traffic can incur data transfer charges on some clouds; zone spread improves availability but can raise cost. Topology-aware routing on Services can keep traffic local where it makes sense.
Helm vs Kustomize basics
You need some way to avoid copy-pasting YAML across environments.
| Helm | Kustomize | |
|---|---|---|
| Model | Templates plus values, packaged as charts | Plain YAML base plus patch overlays |
| Best for | Installing third-party software; apps with many options | Your own services across a few environments |
| Built into kubectl | No (separate CLI) | Yes: kubectl apply -k |
| Release management | Tracks releases, helm rollback, hooks, tests | None; relies on kubectl and Git |
| Debugging | helm template, helm get manifest | kubectl kustomize |
Quick start for each:
# Helm: install, inspect, and upgrade
helm repo add bitnami https://charts.bitnami.com/bitnami
helm template my-redis bitnami/redis -f values.yaml | less # see exactly what will be applied
helm upgrade --install my-redis bitnami/redis -n cache --create-namespace -f values.yaml
helm history my-redis -n cache
helm rollback my-redis 1 -n cache
# Kustomize: build and apply
kubectl kustomize overlays/prod | less
kubectl apply -k overlays/prodCheck the current state of any chart repository you depend on before you pin it in production; chart hosting and catalog policies from large vendors have changed in recent years, so verify that the repository and image sources you use are still maintained and not behind a paywall or deprecated.
A minimal Helm chart structure for a service:
orders-api/
├── Chart.yaml
├── values.yaml
└── templates/
├── deployment.yaml
├── service.yaml
├── hpa.yaml
└── _helpers.tpl# templates/deployment.yaml (fragment) – roll pods when config changes
spec:
template:
metadata:
annotations:
checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}Guideline: pick one default per organization, document it, and render in CI so reviewers see the final YAML. Do not use Helm just to template three environment differences; do not use Kustomize patches to emulate a 40-option product.
Local development
You want a tight inner loop: edit code, see it running in a real cluster in seconds.
Local clusters
| Tool | Notes |
|---|---|
| kind | Kubernetes in Docker; fast, scriptable, great for CI; multi-node supported |
| minikube | Many drivers and add-ons; friendly for beginners |
| k3d | k3s in Docker; very light |
| Docker Desktop or Rancher Desktop Kubernetes | Convenient single-node cluster |
| Remote dev cluster plus namespaces | Closest to production, costs money, needs isolation |
# kind with an ingress-ready node and a local registry is a good default
cat <<'EOF' | kind create cluster --name dev --config=-
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
extraPortMappings:
- containerPort: 80
hostPort: 8080
- containerPort: 443
hostPort: 8443
EOF
kubectl cluster-info --context kind-devInner loop tools
| Tool | What it does | Pick when |
|---|---|---|
| Tilt | Watches code, rebuilds, live-updates containers, great dashboard, Tiltfile in Starlark | Multi-service apps, you want fast syncing without rebuilds |
| Skaffold | Build, push, deploy pipeline with skaffold dev; YAML config; works with Helm, Kustomize, Buildpacks | Simple, CI-friendly, declarative |
| Telepresence or mirrord | Run one service locally while the rest runs in a remote cluster | Big systems that do not fit on a laptop |
| Dev Containers | Reproducible editor environment | Consistent toolchains |
# skaffold.yaml
apiVersion: skaffold/v4beta11
kind: Config
build:
artifacts:
- image: orders-api
docker:
dockerfile: Dockerfile
deploy:
kubectl: {}
manifests:
kustomize:
paths:
- k8s/overlays/dev
portForward:
- resourceType: service
resourceName: orders-api
port: 80
localPort: 8081Check the Skaffold docs for the current schema version string; skaffold fix upgrades older configs.
# Tiltfile (Starlark; Python-like)
docker_build('orders-api', '.',
live_update=[
sync('./src', '/app/src'),
run('npm install', trigger=['package.json']),
])
k8s_yaml(kustomize('k8s/overlays/dev'))
k8s_resource('orders-api', port_forwards=8081)Local development rules
- Keep dev manifests as an overlay of the same base as production so you test the real shape.
- Use the same probes and graceful shutdown locally; they are part of your app.
- Avoid
latestimage tags; in kind you load images withkind load docker-imageor use a local registry. - Seed secrets with dummy values via a dev overlay, never copy production secrets.
The kubectl debugging playbook
When something is wrong, resist the urge to guess. Use the same sequence every time.
The universal first five commands
kubectl get pods -n prod -o wide # status, restarts, node, IP
kubectl describe pod <pod> -n prod # events at the bottom are gold
kubectl logs <pod> -n prod --all-containers --tail=200 # current logs
kubectl logs <pod> -n prod --previous # logs of the crashed container
kubectl get events -n prod --sort-by=.lastTimestamp | tail -30Status decoder
| Status | Meaning | First check |
|---|---|---|
| Pending | Not scheduled or waiting for volumes | describe events: Insufficient cpu or memory, taints, unbound PVC |
| ContainerCreating | Pulling image, mounting volumes, creating sandbox | Events: pull errors, missing ConfigMap or Secret, CNI issues |
| ImagePullBackOff or ErrImagePull | Cannot pull image | Image name, tag, registry credentials |
| CrashLoopBackOff | Container starts then exits repeatedly | logs --previous, exit code |
| Running but not Ready | Readiness probe failing | Probe config, port-forward and curl |
| Terminating (stuck) | Waiting for finalizers or a hung process | Finalizers, SIGTERM handling |
| Evicted | Node pressure | Node conditions, requests too low |
| Completed or Error | Job pods | Job logs, backoffLimit |
Playbook: CrashLoopBackOff
kubectl describe pod <pod> | sed -n '/Last State/,/Ready:/p'
kubectl logs <pod> --previousRead the exit code:
| Exit code | Meaning | Typical cause |
|---|---|---|
| 0 | Exited cleanly | A process that finishes (wrong workload type, or command that daemonizes) |
| 1 | Application error | Exception at boot, bad config, missing env var, cannot reach dependency |
| 2 | Shell misuse | Wrong command or arguments |
| 126 or 127 | Command not executable or not found | Wrong command, missing binary in minimal image |
| 137 | SIGKILL | OOMKilled, or killed after grace period |
| 139 | Segfault | Native crash, wrong architecture |
| 143 | SIGTERM | Normal termination signal, often liveness failure |
Fix flow: wrong env or config, fix manifest; OOMKilled, raise memory or fix leak; liveness killing a slow starter, add a startup probe; missing file or permission denied with readOnlyRootFilesystem, mount an emptyDir for writable paths like /tmp.
If the container dies too fast to inspect, override its command to keep it alive and debug interactively:
kubectl debug <pod> -it --copy-to=debug-copy --container=api -- sh
# or temporarily run a shell in place of the app (copy of the pod, original untouched)Playbook: ImagePullBackOff
kubectl describe pod <pod> | grep -A5 -i "failed to pull"
kubectl get pod <pod> -o jsonpath='{.spec.containers[*].image}'
kubectl get pod <pod> -o jsonpath='{.spec.imagePullSecrets}'| Event message contains | Cause | Fix |
|---|---|---|
not found or manifest unknown | Wrong name or tag; tag not pushed yet | Verify with docker manifest inspect <image> or the registry UI |
unauthorized or authentication required | Missing or wrong pull credentials | Create imagePullSecrets; verify the secret type kubernetes.io/dockerconfigjson and the namespace |
no match for platform in manifest | Built for amd64, node is arm64 (or reverse) | Build multi-arch images |
toomanyrequests | Registry rate limiting | Authenticate, mirror, or use a pull-through cache |
i/o timeout or connection refused | Node cannot reach the registry | Egress rules, proxy, DNS |
kubectl create secret docker-registry regcred \
--docker-server=ghcr.io --docker-username=<user> --docker-password=<token> \
-n prod
kubectl patch serviceaccount default -n prod \
-p '{"imagePullSecrets":[{"name":"regcred"}]}'Playbook: Pending
kubectl describe pod <pod> | sed -n '/Events:/,$p'
kubectl get nodes
kubectl describe node <node> | sed -n '/Allocated resources/,/Events/p'
kubectl get pvc -n prod| Event says | Cause | Fix |
|---|---|---|
Insufficient cpu or Insufficient memory | Requests exceed free capacity | Lower requests, add nodes, check autoscaler (kubectl -n kube-system logs deploy/cluster-autoscaler or Karpenter logs) |
node(s) had untolerated taint | Nodes reserved | Add toleration or schedule elsewhere |
didn't match Pod's node affinity/selector | Label mismatch | Fix selector or label nodes |
pod has unbound immediate PersistentVolumeClaims | PVC not bound | describe pvc, check StorageClass, zone mismatch |
didn't match pod topology spread constraints | Hard spread cannot be met | Relax maxSkew or whenUnsatisfiable |
exceeded quota | Namespace ResourceQuota | kubectl describe quota -n prod |
A pod requesting more than the largest node can ever offer stays Pending forever; compare against kubectl get nodes -o custom-columns=NAME:.metadata.name,CPU:.status.allocatable.cpu,MEM:.status.allocatable.memory.
Playbook: 503s, 502s, and "it works but sometimes fails"
Work from the inside out.
# 1. Does the Service have endpoints?
kubectl get endpointslices -l kubernetes.io/service-name=orders-api -n prod
kubectl get endpoints orders-api -n prod
# 2. Do the pod labels match the Service selector?
kubectl get svc orders-api -n prod -o jsonpath='{.spec.selector}'
kubectl get pods -n prod --show-labels
# 3. Is the port right? targetPort must match the container port (or its name)
kubectl get svc orders-api -n prod -o yaml | grep -A4 ports
# 4. Reach the pod directly, bypassing Service and Ingress
kubectl port-forward pod/<pod> 8081:8080 -n prod
curl -i localhost:8081/readyz
# 5. Reach the Service from inside the cluster
kubectl run tmp --rm -it --image=curlimages/curl -n prod -- curl -i http://orders-api/
# 6. Ingress or Gateway layer
kubectl describe ingress orders -n prod
kubectl get httproute,gateway -A| Symptom | Cause | Fix |
|---|---|---|
| Service has no endpoints | Selector mismatch, or no pods Ready | Fix labels; fix readiness |
| 503 from ingress, pods healthy | Wrong targetPort, wrong Service name or port in Ingress | Match ports; check controller logs |
| 502 or 503 only during deploys | No graceful shutdown | The graceful shutdown recipe above |
| 502 for some requests, steady | App closes idle keep-alive connections earlier than the proxy does | Set app keep-alive timeout greater than the proxy's idle timeout |
| 504 | Upstream slow; proxy timeout | Increase proxy timeout or fix slowness; check CPU throttling |
| Connection reset on a subset of pods | One bad pod still in rotation | Fix readiness; check that pod's logs |
| Works from pod, not from outside | Ingress, Gateway, DNS, TLS, or NetworkPolicy | describe the route; verify DNS and certificate; check NetworkPolicies |
| DNS failures intermittently | CoreDNS overloaded, ndots search path overhead | Check CoreDNS metrics; use FQDNs with trailing dot or lower ndots for chatty clients |
Debugging without a shell: ephemeral containers
Production images are often distroless and have no shell. Attach a debug container that shares the pod's namespaces:
kubectl debug -it pod/<pod> -n prod --image=nicolaka/netshoot --target=api
# Now you can: ss -tlnp, curl localhost:8080, dig, tcpdump (needs capabilities)
# Debug a node (creates a privileged pod on the node; restrict who can do this)
kubectl debug node/<node> -it --image=busyboxEphemeral containers need to be allowed by your cluster's policy, and they are powerful, so treat access as privileged.
Other useful commands
kubectl top pods -n prod --containers # needs metrics-server
kubectl exec -it <pod> -n prod -- sh # if a shell exists
kubectl cp prod/<pod>:/tmp/heap.hprof ./heap.hprof # copy files out
kubectl get pod <pod> -o yaml # full live spec and status
kubectl auth can-i create deployments -n prod # RBAC check
kubectl explain pod.spec.containers.resources # schema docs
kubectl diff -f app.yaml # what would change
kubectl apply -f app.yaml --dry-run=server # server-side validation
kubectl get pods -A --field-selector=status.phase!=Running
kubectl logs -l app.kubernetes.io/name=orders-api --tail=50 --prefix # all pods of an appFor multi-pod tailing, tools like stern are far more pleasant than repeated logs calls.
The decision flow
Pod not running?
Pending ------------> describe: scheduling (resources, taints, PVC, quota)
ImagePull* ---------> image name/tag/credentials/arch
CrashLoopBackOff ---> logs --previous, exit code (137 => memory), probes
Pod running but not Ready? ---> readiness probe: port-forward + curl
Pod Ready but users see errors?
during deploys only ---> graceful shutdown, preStop, maxUnavailable 0
always ----------------> Service endpoints, targetPort, Ingress/Gateway, NetworkPolicy
slowly ----------------> CPU throttling, DB, connection pools, HPA lagCost basics
Cloud Kubernetes bills for nodes, not pods. The goal is to pack the cluster densely with pods that ask for what they need.
| Lever | What to do | Impact |
|---|---|---|
| Right-size requests | Compare requests to real usage; VPA recommendations; delete padding | Largest, most common saving; over-requested clusters often run at 20 to 30 percent real usage |
| Autoscale replicas and nodes | HPA or KEDA plus Cluster Autoscaler or Karpenter; scale non-prod to zero off hours | Pay for load, not for peak |
| Spot or preemptible nodes | Run stateless, interruption-tolerant workloads there, with PDBs and graceful shutdown | Large discounts with interruption risk |
| Commitments | Reserved or savings plans for the steady baseline | Moderate |
| Fewer load balancers | One shared Gateway or ingress instead of a LoadBalancer Service per app | Direct monthly savings |
| Image size and pull policy | Smaller images start faster and pull less | Speeds autoscaling |
| Cross-zone traffic | Topology-aware routing where acceptable | Avoids data transfer charges |
| Log and metric volume | Sample, drop debug logs in prod, limit label cardinality | Often a bigger bill than compute |
| Storage | Delete orphaned PVCs and snapshots; right-size volumes | Quiet leak |
| Visibility | Allocate cost by namespace and label with OpenCost or your cloud's tooling | You cannot reduce what you cannot see |
A cost review checklist
- Sum of requests versus real p95 usage per namespace; flag ratios above 2.
- Idle deployments (zero traffic for 30 days) and unused PVCs, load balancers, and IPs.
- Non-production environments scale down at night and weekends.
- Every workload has requests (BestEffort pods distort scheduling and reporting).
- Cluster capacity (requested versus allocatable, per node) is reviewed monthly.
- Autoscaler
minReplicasis not set to production peak.
Remember the trade-off: right-sizing too tight reintroduces OOMKills and throttling. Save money by removing waste, not by removing headroom.
Putting it together: a production-ready checklist
- Image is pinned to an immutable tag or digest; built for the node architecture.
- Container runs as non-root with a read-only root filesystem where possible (see the container security post for details).
- Requests set for CPU and memory; memory limit set; CPU limit deliberate.
- Startup, readiness, and liveness probes defined, and liveness does not check dependencies.
- App handles SIGTERM, preStop delay set,
terminationGracePeriodSecondssized correctly, exec-form entrypoint. -
maxUnavailable: 0rolling update for user-facing services;progressDeadlineSecondsset. - At least two replicas, a PodDisruptionBudget, and topology spread across zones.
- HPA or KEDA configured with sensible
behavior; minimum replicas cover baseline. - Config and secrets are externalized; a config change rolls pods.
- Logs go to stdout as structured JSON; metrics and traces are exposed.
- Database migrations are backward compatible and run as a Job.
- Manifests are rendered and validated in CI (
kubeconform, policy checks). - A runbook link and an owner label exist on the Deployment.
Start with the baseline manifest in the Deployment section and work through this list. Run a load test, watch throttling and memory, and tune. Then practice the debugging playbook on a kind cluster by breaking things on purpose: a wrong image tag, a failing probe, an impossible resource request. The first time you meet these failures should not be in production at 3 a.m.
Where this usually goes wrong
- Liveness probe that checks the database. One dependency blip restarts every pod.
- No readiness probe. Traffic arrives before the app is ready; rolling updates become outages.
- No CPU requests with an HPA. The HPA shows unknown and never scales.
- Memory limit lower than the real working set. Endless OOMKilled restarts; blame misdirected at "Kubernetes instability".
- Tight CPU limits. Latency spikes and failing probes that look like random network problems.
- Using
latesttags. Nodes cache different versions; rollbacks are impossible to reason about. - Ignoring SIGTERM and shell wrappers. Slow deploys and dropped requests.
- Single replica in production. Any drain or crash is an outage; with a PDB it blocks upgrades.
- Running migrations in every pod at startup. Race conditions and locked tables.
- Storing state in the container filesystem. It disappears with the pod.
- Debugging by deleting pods. You erase the evidence; read
--previouslogs and events first. - Environment config changes without a rollout. Pods keep the old values.
- One namespace for everything with no quotas. One runaway deployment starves others.
- Over-reliance on
kubectl editin production. It bypasses review and, with GitOps, gets reverted. - Treating HPA as a fix for slow code. More replicas of a slow service is an expensive slow service.
When not to use Kubernetes
A small app with modest traffic and one team is better off on a PaaS, serverless containers, or a single VM with Docker Compose. That is cheaper to run and easier to understand, and Kubernetes has a real operational tax. Pure event-handler functions with spiky, tiny workloads may fit serverless functions better. The same goes for stateful data stores as your main workload, since managed databases usually beat self-run operators for most teams.
If no one owns the cluster, think twice. When nobody has time for upgrades (a minor version roughly every four months and a short support window), you will drift into unsupported, insecure territory. Prefer a managed control plane at minimum, or a fully managed container platform. Workloads that need very low latency on dedicated hardware with minimal virtualization layers may be better on bare metal or specialized schedulers, though Kubernetes can host them with care.
And if you are learning to deploy for the first time, build confidence with Docker and a simple PaaS first. Move up when you need scheduling, autoscaling, and multi-service orchestration.
Questions that come up
Should I set CPU limits? Default to a CPU request without a limit for latency-sensitive services, unless your platform mandates limits. If you must, set them well above the request and monitor throttling.
Why does my pod restart at exactly the same interval? Probably a liveness probe or a memory growth pattern. Check describe for probe failures and lastState.terminated.reason for OOMKilled.
How many replicas should I run? At least two, ideally three across zones for anything serving users. Choose minReplicas to survive the loss of a zone at baseline load.
How do I run a one-off task? Use a Job (kubectl create job --from=cronjob/<name> manual-run-1) rather than kubectl exec into a production pod.
Why is kubectl top empty? metrics-server is not installed or not healthy. Install it, and note that it shows near-real-time usage only, not history.
What changed recently that I should check? Verify against the current release notes: ingress-nginx retirement status, in-place pod resize behavior (GA for containers in 1.35, beta for in-place resize of pod-level resources in 1.36), the native preStop sleep action, and any API deprecations affecting your charts (kubectl get --raw /metrics | grep apiserver_requested_deprecated_apis shows deprecated API usage).
Sources and docs
- Kubernetes documentation
- Configure liveness, readiness and startup probes
- Resource management for pods and containers
- Horizontal Pod Autoscaling
- Pod lifecycle and termination
- Disruptions and PodDisruptionBudgets
- Debug running pods and ephemeral containers
- Gateway API
- KEDA
- Vertical Pod Autoscaler
- kind, Tilt, Skaffold
- Kubernetes release notes and blog
- Related on this site: container security hardening for Docker and Kubernetes, GitOps in practice, and event-driven architecture with outbox and idempotency.