Cloud Native › Kubernetes

Configuring Kubernetes probes, resource limits, and preStop

How Kubernetes startup, readiness, and liveness probes, QoS classes, OOMKilled(137), and preStop hooks behave during Pod lifecycle events on a kind cluster.

Configuring Kubernetes probes, resource limits, and preStop

A backend service that boots cleanly under local Docker Compose often hits CrashLoopBackOff, OOMKilled(137), or brief 502 spikes during rolling updates once moved to Kubernetes. This post verifies how startup, readiness, and liveness probes, resource QoS classes, memory limits, and preStop hooks actually behave on a local kind cluster.

All commands and outputs below were recorded on a local 3-node kind cluster (kind v0.33.0, Kubernetes v1.37.0, kubectl v1.36.1, containerd://2.3.4) using busybox:1.36 and python:3.12-alpine.


1. Separating readiness, liveness, and startup probes

On a single Docker host, one HEALTHCHECK reports container health, as covered in my note on Docker HEALTHCHECK and Spring Boot Actuator. Kubernetes splits that responsibility into three probes because kubelet takes a different action when each one fails.

ProbeWhat it checksAction on failureBest fitAnti-pattern to avoid
startupProbeWhether initial boot finishedKills and restarts after thresholdSlow-starting JVM or cache-warming appsRedundant checks on tiny processes that boot in 1–2s
readinessProbeWhether the Pod can take trafficRemoves Pod from EndpointSlice (no restart)Pool warm-up, temporary overload sheddingLong intervals that keep routing traffic to a broken Pod
livenessProbeWhether the process is stuckKills and restarts container (RESTARTS increases)Deadlocks or frozen event loopsChecking external DB/Redis health and triggering mass restarts

Never wire external dependencies like a database or third-party API into livenessProbe. If the database blips for 10 seconds and every Pod fails liveness at once, kubelet restarts healthy application containers in a thundering herd. Use readinessProbe to pull a Pod out of traffic rotation, and reserve livenessProbe for unrecoverable in-process failures.

To verify the split between readiness and liveness, I deployed a Pod and a ClusterIP Service backed by two marker files (/tmp/ready and /tmp/alive).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# probes-demo.yaml
apiVersion: v1
kind: Service
metadata:
  name: probe-svc
  namespace: lab-d4-lifecycle
spec:
  type: ClusterIP
  selector:
    app: probe-demo
  ports:
    - name: http
      port: 80
      targetPort: 8080
---
apiVersion: v1
kind: Pod
metadata:
  name: probe-demo
  namespace: lab-d4-lifecycle
  labels:
    app: probe-demo
spec:
  containers:
    - name: app
      image: busybox:1.36
      command: ["sh", "-c", "touch /tmp/ready /tmp/alive && echo 'started' && sleep 3600"]
      ports:
        - containerPort: 8080
      readinessProbe:
        exec:
          command: ["test", "-f", "/tmp/ready"]
        initialDelaySeconds: 2
        periodSeconds: 2
        failureThreshold: 2
      livenessProbe:
        exec:
          command: ["test", "-f", "/tmp/alive"]
        initialDelaySeconds: 2
        periodSeconds: 2
        failureThreshold: 2

Once the Pod reached READY 1/1, removing /tmp/ready and /tmp/alive in turn produced two distinct outcomes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Initial state
NAME         READY   STATUS    RESTARTS   AGE   IP            NODE
probe-demo   1/1     Running   0          3s    10.244.1.12   k8s-lab-worker2
EndpointSlice: addresses=["10.244.1.12"], conditions={"ready":true,"serving":true,"terminating":false}

# 1) Remove /tmp/ready (readiness fails: removed from traffic, zero restarts)
$ kubectl exec -n lab-d4-lifecycle probe-demo -- rm /tmp/ready
NAME         READY   STATUS    RESTARTS   AGE
probe-demo   0/1     Running   0          9s
EndpointSlice: addresses=["10.244.1.12"], conditions={"ready":false,"serving":false,"terminating":false}

# 2) Remove /tmp/alive (liveness fails: kubelet restarts the container)
$ kubectl exec -n lab-d4-lifecycle probe-demo -- rm /tmp/alive
NAME         READY   STATUS    RESTARTS     AGE
probe-demo   1/1     Running   1 (3s ago)   45s

Events:
  Warning  Unhealthy  33s (x2 over 35s)  kubelet  spec.containers{app}: Liveness probe failed:
  Normal   Killing    33s                kubelet  spec.containers{app}: Container app failed liveness probe, will be restarted
  Warning  Unhealthy  5s (x20 over 40s)  kubelet  spec.containers{app}: Readiness probe failed:
  Normal   Created    3s (x2 over 45s)   kubelet  spec.containers{app}: Container created
  Normal   Started    3s (x2 over 45s)   kubelet  spec.containers{app}: Container started

Deleting /tmp/ready flipped READY to 0/1 and marked the EndpointSlice entry ready: false while keeping RESTARTS at 0. Deleting /tmp/alive triggered a Killing event after two consecutive failures and incremented RESTARTS to 1.


2. Protecting slow-starting containers with startupProbe

JVM and Spring Boot services often need tens of seconds to load classes and initialize beans. If you attach an aggressive livenessProbe directly, kubelet kills the container before boot finishes. Raising initialDelaySeconds on livenessProbe hides the symptom, but it also delays failure detection or guesses wrong when startup time varies.

When startupProbe is configured, kubelet disables both livenessProbe and readinessProbe until startupProbe succeeds once. That gives you a generous startup budget (periodSeconds * failureThreshold) while keeping steady-state liveness checks fast.

Here is a Pod that takes 8 seconds to initialize—twice the 4-second threshold of its livenessProbe—protected by a 20-second startupProbe (2s × 10):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# startup-probe-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: slow-start-demo
  namespace: lab-d4-lifecycle
spec:
  containers:
    - name: app
      image: busybox:1.36
      command: ["sh", "-c", "echo 'initializing (8s)...'; sleep 8; touch /tmp/started /tmp/alive; echo 'ready!'; sleep 3600"]
      startupProbe:
        exec:
          command: ["test", "-f", "/tmp/started"]
        periodSeconds: 2
        failureThreshold: 10
      livenessProbe:
        exec:
          command: ["test", "-f", "/tmp/alive"]
        periodSeconds: 2
        failureThreshold: 2

Inspecting the Pod after 10 seconds confirms zero restarts:

1
2
3
4
5
6
7
8
9
NAME              READY   STATUS    RESTARTS   AGE
slow-start-demo   1/1     Running   0          10s

$ kubectl logs slow-start-demo -n lab-d4-lifecycle
initializing (8s)...
ready!

Events:
  Warning  Unhealthy  2s (x4 over 8s)  kubelet  spec.containers{app}: Startup probe failed:

Kubelet logged four Startup probe failed warnings over 8 seconds, held off the 4-second livenessProbe, and transitioned the Pod cleanly to READY 1/1 with RESTARTS 0.


3. Resource requests, limits, QoS classes, and OOMKilled (137)

In Kubernetes, requests and limits control two different layers:

  • requests tell the scheduler how much capacity a node must reserve before placing the Pod, and map to CPU cgroup weights (cpu.weight) under contention.
  • limits set the hard cgroup ceiling. Exceeding CPU limits only triggers kernel CFS throttling (higher latency), whereas memory is incompressible: crossing limits.memory triggers the kernel OOM Killer (SIGKILL, exit code 137). For JVM heap and native memory sizing under cgroup v2, see my earlier post on Docker resource limits and OOMKilled(137).

Based on every container’s requests and limits, Kubernetes assigns .status.qosClass, which determines eviction order when a node runs low on memory.

QoS ClassRequirementEviction priority under memory pressureRecommended workload
GuaranteedEvery container sets requests == limits for both CPU and memoryLast to be evictedCore APIs, databases, stateful services
BurstableAt least one container sets requests or limits (not Guaranteed)Second (highest overuse vs. request first)Standard web apps with bursty traffic
BestEffortNo container sets any CPU or memory requests or limitsFirst to be evictedDisposable batch jobs, local experiments

Deploying three Pods—qos-guaranteed (100m/64Mi equal), qos-burstable (50m→200m, 32Mi→128Mi), and qos-besteffort (unset)—maps directly to the three classes:

1
2
3
4
5
6
$ kubectl get pods -n lab-d4-lifecycle -l group=qos \
  -o 'custom-columns=NAME:.metadata.name,QOS:.status.qosClass,CPU_REQ:.spec.containers[0].resources.requests.cpu,CPU_LIM:.spec.containers[0].resources.limits.cpu,MEM_REQ:.spec.containers[0].resources.requests.memory,MEM_LIM:.spec.containers[0].resources.limits.memory'
NAME             QOS          CPU_REQ   CPU_LIM   MEM_REQ   MEM_LIM
qos-besteffort   BestEffort   <none>    <none>    <none>    <none>
qos-burstable    Burstable    50m       200m      32Mi      128Mi
qos-guaranteed   Guaranteed   100m      100m      64Mi      64Mi

To confirm the memory ceiling behavior, I ran a python:3.12-alpine Pod capped at limits.memory: 32Mi and allocated a 50MiB bytearray:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# oom-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: oom-demo
  namespace: lab-d4-lifecycle
spec:
  restartPolicy: Never
  containers:
    - name: mem-eater
      image: python:3.12-alpine
      command:
        - python3
        - -c
        - "print('allocating 50MiB...', flush=True); buf = bytearray(50 * 1024 * 1024); print('allocated', len(buf), flush=True)"
      resources:
        requests:
          memory: "16Mi"
        limits:
          memory: "32Mi"
1
2
3
4
5
6
7
8
9
10
$ kubectl get pod oom-demo -n lab-d4-lifecycle
NAME       READY   STATUS      RESTARTS   AGE
oom-demo   0/1     OOMKilled   0          7s

$ kubectl get pod oom-demo -n lab-d4-lifecycle \
  -o jsonpath='reason={.status.containerStatuses[0].state.terminated.reason} exitCode={.status.containerStatuses[0].state.terminated.exitCode}{"\n"}'
reason=OOMKilled exitCode=137

$ kubectl logs oom-demo -n lab-d4-lifecycle
allocating 50MiB...

The kernel terminated the process before allocated could print, recording reason=OOMKilled and exitCode=137.

Tight CPU limits can cause p99 latency spikes from CFS throttling even when the node has idle cores. For latency-sensitive services, setting memory requests == limits gives predictable OOM boundaries, while CPU requests should be sized realistically and CPU limits tuned after load testing.


4. Pod termination flow and preStop graceful shutdown

When a Pod enters Terminating during a rolling update or scale-down, Kubernetes runs two paths in parallel:

sequenceDiagram
    participant API as API Server / EndpointSlice
    participant Proxy as kube-proxy / Gateway
    participant Kubelet as kubelet / Container

    Note over API,Kubelet: kubectl delete pod (Terminating)
    par Route removal
        API->>Proxy: Remove Pod IP from EndpointSlice
        Proxy->>Proxy: Update iptables / IPVS rules
    and Container shutdown
        Kubelet->>Kubelet: Run preStop hook (e.g. sleep 5)
        Note over Kubelet: Delay SIGTERM until routes sync
        Kubelet->>Kubelet: Drain active requests & exit 0
    end

That race is where deployment 502 errors come from. If kubelet sends SIGTERM immediately and your server closes its listening socket before kube-proxy or the Gateway finishes removing the Pod IP, new requests hit a closed port and fail with Connection Refused or 502 Bad Gateway.

The lifecycle.preStop hook runs synchronously before kubelet sends SIGTERM. Adding a short 5–10 second pause gives EndpointSlice updates time to propagate across nodes before the application stops accepting connections. Inside the container, PID 1 still needs to forward or handle SIGTERM cleanly, as explained in my guide to Docker PID 1 and graceful shutdown.

To measure the exact handoff timing, I deployed a Pod with a 5-second preStop sleep and a SIGTERM trap logging UTC timestamps down to the millisecond:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# prestop-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: prestop-demo
  namespace: lab-d4-lifecycle
spec:
  terminationGracePeriodSeconds: 30
  containers:
    - name: app
      image: python:3.12-alpine
      command:
        - sh
        - -c
        - |
          now() { python3 -c "import datetime; print(datetime.datetime.now(datetime.timezone.utc).strftime('%H:%M:%S.%f')[:-3])"; }
          trap 'echo "[$(now)] MAIN: received SIGTERM, draining and exiting cleanly"; exit 0' TERM
          echo "[$(now)] MAIN: started"
          sleep 3600 &
          wait $!
      lifecycle:
        preStop:
          exec:
            command:
              - sh
              - -c
              - |
                now() { python3 -c "import datetime; print(datetime.datetime.now(datetime.timezone.utc).strftime('%H:%M:%S.%f')[:-3])"; }
                echo "[$(now)] PRESTOP: hook started, sleeping 5s for endpoint propagation" > /proc/1/fd/1
                sleep 5
                echo "[$(now)] PRESTOP: hook finished" > /proc/1/fd/1

Running kubectl delete pod prestop-demo while tailing kubectl logs -f prestop-demo produced:

1
2
3
4
[07:03:24.569] MAIN: started
[07:03:26.648] PRESTOP: hook started, sleeping 5s for endpoint propagation
[07:03:31.661] PRESTOP: hook finished
[07:03:31.677] MAIN: received SIGTERM, draining and exiting cleanly

The preStop hook started at 07:03:26.648, finished 5.013 seconds later at 07:03:31.661, and kubelet delivered SIGTERM to the main process 0.016 seconds after that (07:03:31.677).

Keep in mind that preStop only delays SIGTERM to cover endpoint propagation. Draining in-flight HTTP requests and keep-alive connections still depends on the application server’s own shutdown handling (such as server.shutdown=graceful and spring.lifecycle.timeout-per-shutdown-phase in Spring Boot).


5. Production pitfalls and checklist

Three traps that break production rollouts

  1. Underestimating terminationGracePeriodSeconds: The default 30-second countdown starts when preStop begins, not when SIGTERM arrives. If preStop sleeps 20 seconds and the app needs 15 seconds to drain, kubelet sends SIGKILL (exit 137) at 30 seconds. Always set terminationGracePeriodSeconds above preStop duration + app drain timeout + buffer.
  2. External checks inside livenessProbe: Putting database or downstream HTTP checks in livenessProbe turns a brief dependency blip into a cluster-wide restart storm. Keep external health checks in readinessProbe or out-of-band monitoring.
  3. Missing shell binaries in minimal images: Distroless images don’t ship sh or sleep, so exec: ["sh", "-c", "sleep 5"] fails. On Kubernetes 1.30+, use the native lifecycle.preStop.sleep action (sleep: { seconds: 5 }) or an httpGet hook instead.

Before promoting a Deployment to production, check these five items:

  • Slow-starting workloads use startupProbe so livenessProbe never kills them during boot.
  • readinessProbe controls traffic routing while livenessProbe checks only unrecoverable in-process failures.
  • Every container defines at least requests and a memory limits value to stay out of BestEffort eviction.
  • terminationGracePeriodSeconds is larger than preStop sleep plus the application’s graceful shutdown timeout.
  • kubectl delete pod logs confirm the container receives SIGTERM and exits with code 0 rather than timing out to 137.

References

Kubernetes lets you define probes to continuously monitor the health of containers in a Pod. A probe is a diagnostic performed periodically by the kubelet on a container. To perform a diagnostic, the kubelet either executes code within the container or makes a network request. Based on the probe results, Kubernetes can restart unhealthy containers or stop sending traffic to containers that are not ready.
This page describes the lifecycle of a Pod. Pods follow a defined lifecycle, starting in the Pending phase, moving through Running if at least one of its primary containers starts OK, and then through either the Succeeded or Failed phases depending on whether any container in the Pod terminated in failure. While a Pod runs, the kubelet manages containers and translates the Pod's spec for the container runtime. The kubelet also manages executing probes that track the health of your application.
This page introduces Quality of Service (QoS) classes in Kubernetes, and explains how Kubernetes assigns a QoS class to each Pod as a consequence of the resource constraints that you specify for the containers in that Pod. Kubernetes relies on this classification to make decisions about which Pods to evict when there are not enough available resources on a Node. Quality of Service classesKubernetes classifies the Pods that you run and allocates each Pod into a specific quality of service (QoS) class. Kubernetes uses that classification to influence how different pods are handled. Kubernetes does this classification based on the resource requests of the Containers in that Pod, along with how those requests relate to resource limits. This is known as Quality of Service (QoS) class. Kubernetes assigns every Pod a QoS class based on the resource requests and limits of its component Containers. QoS classes are used by Kubernetes to decide which Pods to evict from a Node experiencing Node Pressure. The possible QoS classes are Guaranteed, Burstable, and BestEffort. When a Node runs out of resources, Kubernetes will first evict BestEffort Pods running on that Node, followed by Burstable and finally Guaranteed Pods. When this eviction is due to resource pressure, only Pods exceeding resource requests are candidates for eviction.
This post is licensed under CC BY 4.0 by the author.