Skip to content
Derar Sattouf

Kubernetes for Developers: Probes, Resources and Autoscaling

Updated DevOps & cloud

Kubernetes for Developers: Probes, Resources and Autoscaling

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 traffic

Vocabulary cheat sheet

TermMeaningDeveloper relevance
PodSmallest deployable unit; one or more containersYour app runs here
ReplicaSetKeeps N pods runningYou rarely touch it directly
DeploymentManages ReplicaSets and rolling updatesYour default workload type
StatefulSetStable identity and storage per replicaDatabases, brokers; avoid for app code
Job and CronJobRun to completion, scheduledMigrations, batch
DaemonSetOne pod per nodeAgents, log shippers
ServiceStable virtual IP and DNS name for podsHow other pods call you
Ingress and Gateway APIExternal HTTP routingHow users call you
NamespaceScope for names, quotas, and RBACEnvironment or team boundary
ConfigMap and SecretConfiguration and sensitive dataEnv vars and mounted files
NodeA machine running podsUsually 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: http

Inside 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.

IngressGateway API
MaturityStable, frozen feature setGA core resources (v1), growing extension set
Routing featuresHost and path; the rest via vendor annotationsHeader and query matching, weights, redirects, rewrites as first-class fields
Ownership modelOne object mixes platform and app concernsPlatform owns Gateway, app teams own HTTPRoute
PortabilityAnnotations differ per controllerStandardized fields, fewer annotations
Use whenExisting clusters, simple needsNew 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: 80

ConfigMaps 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

ProbeQuestion it answersOn failureTypical endpoint
StartupHas the app finished booting?Keep waiting; after the failure threshold, restart the container. Disables liveness and readiness until it succeedsThe same as liveness
ReadinessShould this pod receive traffic right now?Remove from Service endpoints (no restart)Checks the app can serve: warm caches loaded, critical local state ready
LivenessIs this process wedged beyond recovery?Kill and restart the containerA trivial check that the event loop responds

Rules that prevent outages

  1. 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".
  2. 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.
  3. Use a startup probe for slow boots instead of a huge initialDelaySeconds on liveness. A startup probe with periodSeconds: 3 and failureThreshold: 30 gives 90 seconds to boot, but a fast boot succeeds immediately and probing switches to the tighter intervals.
  4. Make timeouts realistic. The default timeoutSeconds is 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.
  5. 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.
  6. Distinguish /livez from /readyz. They are different questions; do not point both at /health.
  7. Probe a port the app owns, not through the Service. Probes run against the pod IP from the kubelet.
  8. Return quickly and cheaply. A probe that allocates, logs, and hits three downstreams adds load precisely when load is highest.

Probe handler types

TypeUse whenWatch out for
httpGetHTTP services (default choice)Any status 200 to 399 passes
tcpSocketNon-HTTP serversOnly proves the port is open
grpcgRPC services implementing the gRPC health protocolRequires the standard health service
execScripts, legacySpawns 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

SymptomLikely causeFix
Restarts roughly every few minutes under loadLiveness timeout too tight, or CPU throttling delays responseRaise timeoutSeconds, add CPU requests, relax thresholds
Pod never becomes Ready, no restartsReadiness endpoint failing, or wrong port or pathkubectl describe pod, check probe events; kubectl port-forward and curl
Restart loop right after startLiveness begins before boot completesAdd a startup probe
All pods restart togetherLiveness checks a shared dependencyRemove dependency checks from liveness
Readiness probe failed: connection refused at bootApp binds to 127.0.0.1Bind 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 classHow you get itEviction priority
GuaranteedEvery container has CPU and memory requests equal to limitsLast to be evicted
BurstableAt least one request or limit set, but not GuaranteedMiddle; evicted based on how much usage exceeds requests
BestEffortNo requests or limits at allFirst to be evicted

A sensible default policy

resources:
  requests:
    cpu: 250m
    memory: 384Mi
  limits:
    memory: 384Mi

That 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_usec

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

CauseFix
Limit simply too low for the working setMeasure 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 limitUse -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 highSet --max-old-space-size to roughly 75 percent of the limit (in MiB)
Memory leakProfile; a leak will eventually hit any limit. Use heap snapshots, pprof, or your runtime's profiler
Page cache or tmpfs countedemptyDir 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

  1. Deploy with generous values in a staging environment.
  2. Run a realistic load test that includes peak traffic shapes.
  3. Record p95 CPU and p99 memory per pod from metrics.
  4. Set CPU request near p90 to p95 of observed CPU; set memory request and limit to peak plus headroom.
  5. Run the Vertical Pod Autoscaler in recommendation mode (updateMode: "Off") for a week of production data and compare.
  6. 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 only
kubectl describe vpa orders-api
# Look at "Recommendation: Target / Lower Bound / Upper Bound" per container

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

Design 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 behavior block 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 HPAScaleToZero feature 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-auth

The 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

SituationUse
CPU-bound stateless web serviceHPA on CPU usage
I/O-bound web serviceHPA on requests per second or latency via custom metrics
Queue or stream consumersKEDA on queue length or consumer lag
Scheduled load (business hours)KEDA cron scaler or a scheduled scale of min replicas
Unknown right sizeVPA in recommendation mode first
Need scale to zeroKEDA (or HPA scale-to-zero if enabled in your version)
Stateful single-writer workloadVertical resize, not horizontal

Autoscaling lab

  1. Deploy the Deployment with CPU requests set and the HPA above.
  2. Confirm the HPA can read metrics: kubectl get hpa orders-api should show a number, not <unknown>. If unknown, install metrics-server and verify kubectl top pods works.
  3. Generate load: kubectl run load --rm -it --image=busybox -- /bin/sh -c "while true; do wget -q -O- http://orders-api/; done".
  4. Watch: kubectl get hpa orders-api -w and kubectl get pods -w.
  5. 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:

ParameterMeaningRecommended
maxSurgeExtra pods allowed above desired during rollout1, or 25 percent
maxUnavailablePods allowed to be unavailable during rollout0 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-api

If 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

StrategyWhat it givesTooling
Rolling (default)Gradual replacement, no extra toolingDeployment
RecreateOld pods all stop, then new start; downtime, but needed for singletons with exclusive stateDeployment strategy.type: Recreate
Blue-greenTwo full environments, switch the Service or routeArgo Rollouts, manual Service selector flip
CanaryGradual traffic shift with metric analysisArgo 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: 5

Database 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 running

The 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

  1. preStop sleep (5 to 15 seconds) to cover propagation delay. Newer Kubernetes versions support a native sleep action in lifecycle.preStop (check that it is available in your version), which also works with distroless images that lack a sleep binary. The exec form needs a shell or sleep in the image.
  2. Handle SIGTERM in the app: stop accepting new connections, finish in-flight requests, close pools, then exit.
  3. Set terminationGracePeriodSeconds greater 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: 10

Node.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-api

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

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

MechanismUse for
Topology spread constraintsEven 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 nodeSelectorPlace on specific hardware (GPU, arm64, spot)
Taints and tolerationsReserve nodes for specific workloads
Priority classesWhich 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.

HelmKustomize
ModelTemplates plus values, packaged as chartsPlain YAML base plus patch overlays
Best forInstalling third-party software; apps with many optionsYour own services across a few environments
Built into kubectlNo (separate CLI)Yes: kubectl apply -k
Release managementTracks releases, helm rollback, hooks, testsNone; relies on kubectl and Git
Debugginghelm template, helm get manifestkubectl 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/prod

Check 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

ToolNotes
kindKubernetes in Docker; fast, scriptable, great for CI; multi-node supported
minikubeMany drivers and add-ons; friendly for beginners
k3dk3s in Docker; very light
Docker Desktop or Rancher Desktop KubernetesConvenient single-node cluster
Remote dev cluster plus namespacesClosest 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-dev

Inner loop tools

ToolWhat it doesPick when
TiltWatches code, rebuilds, live-updates containers, great dashboard, Tiltfile in StarlarkMulti-service apps, you want fast syncing without rebuilds
SkaffoldBuild, push, deploy pipeline with skaffold dev; YAML config; works with Helm, Kustomize, BuildpacksSimple, CI-friendly, declarative
Telepresence or mirrordRun one service locally while the rest runs in a remote clusterBig systems that do not fit on a laptop
Dev ContainersReproducible editor environmentConsistent 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: 8081

Check 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 latest image tags; in kind you load images with kind load docker-image or 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 -30

Status decoder

StatusMeaningFirst check
PendingNot scheduled or waiting for volumesdescribe events: Insufficient cpu or memory, taints, unbound PVC
ContainerCreatingPulling image, mounting volumes, creating sandboxEvents: pull errors, missing ConfigMap or Secret, CNI issues
ImagePullBackOff or ErrImagePullCannot pull imageImage name, tag, registry credentials
CrashLoopBackOffContainer starts then exits repeatedlylogs --previous, exit code
Running but not ReadyReadiness probe failingProbe config, port-forward and curl
Terminating (stuck)Waiting for finalizers or a hung processFinalizers, SIGTERM handling
EvictedNode pressureNode conditions, requests too low
Completed or ErrorJob podsJob logs, backoffLimit

Playbook: CrashLoopBackOff

kubectl describe pod <pod> | sed -n '/Last State/,/Ready:/p'
kubectl logs <pod> --previous

Read the exit code:

Exit codeMeaningTypical cause
0Exited cleanlyA process that finishes (wrong workload type, or command that daemonizes)
1Application errorException at boot, bad config, missing env var, cannot reach dependency
2Shell misuseWrong command or arguments
126 or 127Command not executable or not foundWrong command, missing binary in minimal image
137SIGKILLOOMKilled, or killed after grace period
139SegfaultNative crash, wrong architecture
143SIGTERMNormal 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 containsCauseFix
not found or manifest unknownWrong name or tag; tag not pushed yetVerify with docker manifest inspect <image> or the registry UI
unauthorized or authentication requiredMissing or wrong pull credentialsCreate imagePullSecrets; verify the secret type kubernetes.io/dockerconfigjson and the namespace
no match for platform in manifestBuilt for amd64, node is arm64 (or reverse)Build multi-arch images
toomanyrequestsRegistry rate limitingAuthenticate, mirror, or use a pull-through cache
i/o timeout or connection refusedNode cannot reach the registryEgress 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 saysCauseFix
Insufficient cpu or Insufficient memoryRequests exceed free capacityLower requests, add nodes, check autoscaler (kubectl -n kube-system logs deploy/cluster-autoscaler or Karpenter logs)
node(s) had untolerated taintNodes reservedAdd toleration or schedule elsewhere
didn't match Pod's node affinity/selectorLabel mismatchFix selector or label nodes
pod has unbound immediate PersistentVolumeClaimsPVC not bounddescribe pvc, check StorageClass, zone mismatch
didn't match pod topology spread constraintsHard spread cannot be metRelax maxSkew or whenUnsatisfiable
exceeded quotaNamespace ResourceQuotakubectl 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
SymptomCauseFix
Service has no endpointsSelector mismatch, or no pods ReadyFix labels; fix readiness
503 from ingress, pods healthyWrong targetPort, wrong Service name or port in IngressMatch ports; check controller logs
502 or 503 only during deploysNo graceful shutdownThe graceful shutdown recipe above
502 for some requests, steadyApp closes idle keep-alive connections earlier than the proxy doesSet app keep-alive timeout greater than the proxy's idle timeout
504Upstream slow; proxy timeoutIncrease proxy timeout or fix slowness; check CPU throttling
Connection reset on a subset of podsOne bad pod still in rotationFix readiness; check that pod's logs
Works from pod, not from outsideIngress, Gateway, DNS, TLS, or NetworkPolicydescribe the route; verify DNS and certificate; check NetworkPolicies
DNS failures intermittentlyCoreDNS overloaded, ndots search path overheadCheck 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=busybox

Ephemeral 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 app

For 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 lag

Cost basics

Cloud Kubernetes bills for nodes, not pods. The goal is to pack the cluster densely with pods that ask for what they need.

LeverWhat to doImpact
Right-size requestsCompare requests to real usage; VPA recommendations; delete paddingLargest, most common saving; over-requested clusters often run at 20 to 30 percent real usage
Autoscale replicas and nodesHPA or KEDA plus Cluster Autoscaler or Karpenter; scale non-prod to zero off hoursPay for load, not for peak
Spot or preemptible nodesRun stateless, interruption-tolerant workloads there, with PDBs and graceful shutdownLarge discounts with interruption risk
CommitmentsReserved or savings plans for the steady baselineModerate
Fewer load balancersOne shared Gateway or ingress instead of a LoadBalancer Service per appDirect monthly savings
Image size and pull policySmaller images start faster and pull lessSpeeds autoscaling
Cross-zone trafficTopology-aware routing where acceptableAvoids data transfer charges
Log and metric volumeSample, drop debug logs in prod, limit label cardinalityOften a bigger bill than compute
StorageDelete orphaned PVCs and snapshots; right-size volumesQuiet leak
VisibilityAllocate cost by namespace and label with OpenCost or your cloud's toolingYou 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 minReplicas is 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, terminationGracePeriodSeconds sized correctly, exec-form entrypoint.
  • maxUnavailable: 0 rolling update for user-facing services; progressDeadlineSeconds set.
  • 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

  1. Liveness probe that checks the database. One dependency blip restarts every pod.
  2. No readiness probe. Traffic arrives before the app is ready; rolling updates become outages.
  3. No CPU requests with an HPA. The HPA shows unknown and never scales.
  4. Memory limit lower than the real working set. Endless OOMKilled restarts; blame misdirected at "Kubernetes instability".
  5. Tight CPU limits. Latency spikes and failing probes that look like random network problems.
  6. Using latest tags. Nodes cache different versions; rollbacks are impossible to reason about.
  7. Ignoring SIGTERM and shell wrappers. Slow deploys and dropped requests.
  8. Single replica in production. Any drain or crash is an outage; with a PDB it blocks upgrades.
  9. Running migrations in every pod at startup. Race conditions and locked tables.
  10. Storing state in the container filesystem. It disappears with the pod.
  11. Debugging by deleting pods. You erase the evidence; read --previous logs and events first.
  12. Environment config changes without a rollout. Pods keep the old values.
  13. One namespace for everything with no quotas. One runaway deployment starves others.
  14. Over-reliance on kubectl edit in production. It bypasses review and, with GitOps, gets reverted.
  15. 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