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.
A backend service that boots cleanly under local Docker Compose often hits
CrashLoopBackOff,OOMKilled(137), or brief502spikes during rolling updates once moved to Kubernetes. This post verifies howstartup,readiness, andlivenessprobes, resource QoS classes, memory limits, andpreStophooks actually behave on a localkindcluster.
All commands and outputs below were recorded on a local 3-node
kindcluster (kind v0.33.0, Kubernetesv1.37.0,kubectl v1.36.1,containerd://2.3.4) usingbusybox:1.36andpython: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.
| Probe | What it checks | Action on failure | Best fit | Anti-pattern to avoid |
|---|---|---|---|---|
startupProbe | Whether initial boot finished | Kills and restarts after threshold | Slow-starting JVM or cache-warming apps | Redundant checks on tiny processes that boot in 1–2s |
readinessProbe | Whether the Pod can take traffic | Removes Pod from EndpointSlice (no restart) | Pool warm-up, temporary overload shedding | Long intervals that keep routing traffic to a broken Pod |
livenessProbe | Whether the process is stuck | Kills and restarts container (RESTARTS increases) | Deadlocks or frozen event loops | Checking 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:
requeststell the scheduler how much capacity a node must reserve before placing the Pod, and map to CPU cgroup weights (cpu.weight) under contention.limitsset the hard cgroup ceiling. Exceeding CPU limits only triggers kernel CFS throttling (higher latency), whereas memory is incompressible: crossinglimits.memorytriggers the kernel OOM Killer (SIGKILL, exit code137). 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 Class | Requirement | Eviction priority under memory pressure | Recommended workload |
|---|---|---|---|
Guaranteed | Every container sets requests == limits for both CPU and memory | Last to be evicted | Core APIs, databases, stateful services |
Burstable | At least one container sets requests or limits (not Guaranteed) | Second (highest overuse vs. request first) | Standard web apps with bursty traffic |
BestEffort | No container sets any CPU or memory requests or limits | First to be evicted | Disposable 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
limitscan cause p99 latency spikes from CFS throttling even when the node has idle cores. For latency-sensitive services, setting memoryrequests == limitsgives predictable OOM boundaries, while CPUrequestsshould be sized realistically and CPUlimitstuned 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
- Underestimating
terminationGracePeriodSeconds: The default 30-second countdown starts whenpreStopbegins, not whenSIGTERMarrives. IfpreStopsleeps 20 seconds and the app needs 15 seconds to drain, kubelet sendsSIGKILL(exit137) at 30 seconds. Always setterminationGracePeriodSecondsabovepreStop duration + app drain timeout + buffer.- External checks inside
livenessProbe: Putting database or downstream HTTP checks inlivenessProbeturns a brief dependency blip into a cluster-wide restart storm. Keep external health checks inreadinessProbeor out-of-band monitoring.- Missing shell binaries in minimal images: Distroless images don’t ship
shorsleep, soexec: ["sh", "-c", "sleep 5"]fails. On Kubernetes 1.30+, use the nativelifecycle.preStop.sleepaction (sleep: { seconds: 5 }) or anhttpGethook instead.
Before promoting a Deployment to production, check these five items:
- Slow-starting workloads use
startupProbesolivenessProbenever kills them during boot. readinessProbecontrols traffic routing whilelivenessProbechecks only unrecoverable in-process failures.- Every container defines at least
requestsand a memorylimitsvalue to stay out ofBestEfforteviction. terminationGracePeriodSecondsis larger thanpreStopsleep plus the application’s graceful shutdown timeout.kubectl delete podlogs confirm the container receivesSIGTERMand exits with code0rather than timing out to137.