Overview and What You Will Learn
A Kubernetes probe is a periodic health check that the kubelet runs against a container. There are three kinds. A startup probe asks whether the application has finished starting, a liveness probe asks whether it is still working and should be restarted if not, and a readiness probe asks whether it can receive traffic right now. Without probes, Kubernetes only knows that the container process exists, so a hung API, a service that cannot reach its dependencies, and a pod still warming its cache all look healthy. In this lab, you will trigger a liveness restart, compare a rolling update with and without a readiness probe under live traffic, and pull a pod out of a Service without restarting it.
- Explaining what startup, liveness and readiness probes do and what each failure causes
- Choosing a probe mechanism: HTTP, TCP, gRPC or exec
- Tuning probe timing without causing false restarts
- Designing health endpoints that report real state
- Combining probes,
maxUnavailable: 0and graceful shutdown for zero-downtime rollouts - Configuring probes for Node.js, Spring Boot and PostgreSQL
Why This Matters in Production
At a company like Spotify, a deployment rolls a new API version across dozens of pods at peak traffic. If the new pods pass for ready as soon as the process starts, they receive requests before their caches are loaded and users see a burst of 500 errors. A readiness probe holds traffic on the old pods until each new pod can actually serve, and a correct shutdown sequence stops the old pods from dropping in-flight requests. Together they are the most effective configuration for zero-downtime deployments.
Core Principles
The three probes answer different questions and cause different actions:
| Probe | Question | On failure |
|---|---|---|
| Startup | Has the app finished starting? | Container is killed once the budget runs out |
| Liveness | Is the app alive and not hung? | Container is restarted |
| Readiness | Can the app take traffic now? | Pod is removed from Service endpoints, no restart |
While a startup probe is running, the liveness and readiness probes are disabled. Once it succeeds, the other two run for the rest of the pod's life, independently of each other.
succeeds?} SP -->|Budget exhausted| K[Container killed
and restarted] SP -->|Yes| BOTH[Liveness and readiness
run in parallel] BOTH --> L{Liveness fails
repeatedly?} BOTH --> R{Readiness fails?} L -->|Yes| K R -->|Yes| E[Removed from
Service endpoints] classDef start fill:#D1FAE5,color:#1E293B classDef dec fill:#F97316,color:#FFFFFF classDef bad fill:#EF4444,color:#FFFFFF classDef ok fill:#326CE5,color:#FFFFFF class S start class SP,L,R dec class K,E bad class BOTH ok
During a rolling update, readiness decides when traffic moves. With maxUnavailable: 0 and a maxSurge of at least 1, Kubernetes starts a new pod first and removes an old one only after the new pod reports ready:
not ready] W --> RD[Readiness passes
added to Service] RD --> O[Old pod removed
after drain] classDef step fill:#326CE5,color:#FFFFFF classDef warm fill:#F97316,color:#FFFFFF classDef done fill:#10B981,color:#FFFFFF class N,RD step class W warm class O done
Each probe supports four mechanisms. HTTP succeeds on a status from 200 to 399. TCP succeeds when a connection opens. gRPC calls the standard gRPC health protocol. Exec succeeds when a command exits with code 0. Exec probes start a process on every check, so they are the most expensive at scale.
The timing fields have these defaults:
| Field | Default | Meaning |
|---|---|---|
periodSeconds |
10 | How often to probe |
timeoutSeconds |
1 | How long to wait for an answer |
failureThreshold |
3 | Consecutive failures before acting |
initialDelaySeconds defaults to 0 and successThreshold defaults to 1. Liveness and startup probes must use a successThreshold of 1, while readiness can use a higher value to require several passes before a pod rejoins a Service. A startup probe's total budget is failureThreshold multiplied by periodSeconds.
Detailed Step-by-Step Practical Lab
This lab needs any Kubernetes cluster and kubectl. The first workload uses the Kubernetes project's own test image, which serves a health endpoint that starts failing on purpose.
- Create a namespace:
kubectl create namespace probes-labkubectl config set-context --current --namespace=probes-lab- See a liveness probe restart a container. The test image returns 200 on
/healthzfor ten seconds and then returns 500, simulating a hung application:
cat << 'EOF' | kubectl apply -f -apiVersion: v1kind: Podmetadata: name: liveness-demospec: containers: - name: app image: registry.k8s.io/e2e-test-images/agnhost:2.40 args: ["liveness"] livenessProbe: httpGet: path: /healthz port: 8080 initialDelaySeconds: 3 periodSeconds: 3 failureThreshold: 3EOF kubectl get pod liveness-demo -wAfter about 20 seconds the RESTARTS column increases. Stop the watch with Ctrl+C and read why:
kubectl describe pod liveness-demo | grep -A8 EventsThe events show Liveness probe failed: HTTP probe failed with statuscode: 500 followed by a restart.
- Create two identical Deployments that take 20 seconds to warm up, one without probes and one with startup, readiness and liveness probes. The container waits 20 seconds before it creates the
ready.htmlfile and starts nginx, which simulates cache warming. Both usemaxUnavailable: 0:
cat << 'EOF' | kubectl apply -f -apiVersion: apps/v1kind: Deploymentmetadata: name: web-noprobespec: replicas: 3 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0 selector: matchLabels: app: web-noprobe template: metadata: labels: app: web-noprobe spec: containers: - name: web image: nginx:1.27-alpine command: - sh - -c - | sleep 20 echo ok > /usr/share/nginx/html/ready.html exec nginx -g "daemon off;" ports: - containerPort: 80EOF cat << 'EOF' | kubectl apply -f -apiVersion: apps/v1kind: Deploymentmetadata: name: web-probespec: replicas: 3 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0 selector: matchLabels: app: web-probe template: metadata: labels: app: web-probe spec: containers: - name: web image: nginx:1.27-alpine command: - sh - -c - | sleep 20 echo ok > /usr/share/nginx/html/ready.html exec nginx -g "daemon off;" ports: - containerPort: 80 startupProbe: tcpSocket: port: 80 periodSeconds: 2 failureThreshold: 30 readinessProbe: httpGet: path: /ready.html port: 80 periodSeconds: 2 failureThreshold: 3 livenessProbe: httpGet: path: / port: 80 periodSeconds: 10 failureThreshold: 3EOF kubectl expose deployment web-noprobe --port=80kubectl expose deployment web-probe --port=80sleep 45kubectl get podsThe pods of web-noprobe show 1/1 as soon as the container starts, even though nginx is not listening yet. The pods of web-probe show 0/1 until the readiness probe passes.
- Roll out a change under live traffic to both Deployments and count failed requests. Each load pod requests its Service about four times a second and prints
FAILwhen a request fails:
for APP in noprobe probe; do kubectl run load-$APP --image=busybox:1.36 --restart=Never -- sh -c \ "for i in \$(seq 1 480); do wget -q -T 1 -O /dev/null http://web-$APP/ready.html || echo FAIL; sleep 0.25; done; echo finished"done sleep 5kubectl set env deployment/web-noprobe RELEASE=2kubectl set env deployment/web-probe RELEASE=2 kubectl rollout status deployment/web-noprobe --timeout=180skubectl rollout status deployment/web-probe --timeout=180s- When the load pods finish, compare the results:
kubectl wait --for=jsonpath='{.status.phase}'=Succeeded pod/load-noprobe pod/load-probe --timeout=240s echo "Failures without probes: $(kubectl logs load-noprobe | grep -c FAIL)"echo "Failures with probes: $(kubectl logs load-probe | grep -c FAIL)"The Deployment without probes drops requests while new pods warm up, and the one with a readiness probe should show none or almost none. This is exactly what the readiness probe buys you.
- See readiness remove a pod from a Service without restarting it. Delete the file that the readiness probe checks on one pod:
POD=$(kubectl get pod -l app=web-probe -o jsonpath='{.items[0].metadata.name}') kubectl exec $POD -- rm /usr/share/nginx/html/ready.htmlsleep 8kubectl get pods -l app=web-probekubectl get endpoints web-probeThe pod shows 0/1 ready with 0 restarts, and the endpoints list has only two addresses. Put the file back and it rejoins:
kubectl exec $POD -- sh -c 'echo ok > /usr/share/nginx/html/ready.html'sleep 8kubectl get endpoints web-probe- Clean up:
kubectl config set-context --current --namespace=defaultkubectl delete namespace probes-labDesigning Health Endpoints
A probe is only as good as the endpoint behind it. Keep liveness cheap and local, and make readiness describe whether this pod can serve right now. The Node.js example below uses flags that the application sets, and it fails readiness during shutdown so traffic drains first:
// health.jsconst express = require('express');const router = express.Router(); const state = { fatal: false, shuttingDown: false, cacheWarm: false }; // Liveness: can this process respond, and is it in an unrecoverable state?router.get('/healthz', (req, res) => { if (state.fatal) { return res.status(503).json({ status: 'fatal' }); } res.status(200).json({ status: 'alive' });}); // Readiness: can THIS pod serve requests right now?router.get('/ready', (req, res) => { if (state.shuttingDown) { return res.status(503).json({ status: 'shutting-down' }); } if (!state.cacheWarm) { return res.status(503).json({ status: 'warming' }); } res.status(200).json({ status: 'ready' });}); module.exports = { router, state };// server.jsconst server = app.listen(8080); process.on('SIGTERM', () => { health.state.shuttingDown = true; // readiness starts failing at once setTimeout(() => { server.close(() => process.exit(0)); // finish in-flight requests, then exit }, 5000); // give endpoint removal time to spread});For Spring Boot, the Actuator provides separate liveness and readiness groups. Add dependencies to the readiness group only after reading the warning below, and enable graceful shutdown:
management: endpoint: health: probes: enabled: true show-details: never group: liveness: include: livenessState readiness: include: readinessState endpoints: web: exposure: include: health, info, prometheus server: shutdown: graceful spring: lifecycle: timeout-per-shutdown-phase: 30sA Production Deployment Template
This Deployment combines all the pieces: a startup probe for slow starts, separate liveness and readiness endpoints, maxUnavailable: 0, a preStop pause so endpoint removal reaches every node, and a shutdown window longer than the pause plus request draining:
apiVersion: apps/v1kind: Deploymentmetadata: name: order-api namespace: productionspec: replicas: 5 minReadySeconds: 10 progressDeadlineSeconds: 600 strategy: type: RollingUpdate rollingUpdate: maxSurge: 2 maxUnavailable: 0 selector: matchLabels: app: order-api template: metadata: labels: app: order-api spec: terminationGracePeriodSeconds: 40 containers: - name: order-api image: registry.devops.in/order-api:v6.2.1 ports: - containerPort: 8080 resources: requests: cpu: 250m memory: 256Mi limits: memory: 512Mi lifecycle: preStop: exec: command: ["sh", "-c", "sleep 8"] startupProbe: httpGet: path: /healthz port: 8080 periodSeconds: 5 failureThreshold: 60 livenessProbe: httpGet: path: /healthz port: 8080 periodSeconds: 15 timeoutSeconds: 5 failureThreshold: 3 readinessProbe: httpGet: path: /ready port: 8080 periodSeconds: 5 timeoutSeconds: 3 failureThreshold: 3 successThreshold: 2The startup budget here is 60 attempts every 5 seconds, which is five minutes. If a rollout stalls, kubectl rollout status reports it and kubectl rollout undo deployment/order-api returns to the previous version.
Probes for Databases and Brokers
Restarting a database that is merely slow can do more harm than leaving it alone, so use a startup probe for recovery time and generous liveness thresholds. For PostgreSQL, pg_isready works as an exec probe, and a plain TCP check suits brokers such as Kafka:
startupProbe: exec: command: ["pg_isready", "-U", "postgres", "-h", "localhost"] periodSeconds: 10 failureThreshold: 60 livenessProbe: exec: command: ["pg_isready", "-U", "postgres", "-h", "localhost"] periodSeconds: 10 timeoutSeconds: 5 failureThreshold: 6 readinessProbe: exec: command: ["pg_isready", "-U", "postgres", "-h", "localhost"] periodSeconds: 5 timeoutSeconds: 3 failureThreshold: 3readinessProbe: tcpSocket: port: 9092 periodSeconds: 10 failureThreshold: 3Production Best Practices & Common Pitfalls
Common MistakeMaking the liveness probe check external dependencies such as the database. When the database has a short outage, every pod fails liveness and restarts together, which turns a brief dependency problem into a full outage. Liveness should test only the pod itself.
SecurityHealth endpoints are often reachable more widely than you intend. Return short status values only, never connection strings, internal addresses or stack traces, and keep detailed diagnostics on a separate protected endpoint.
TipUse different endpoints for liveness and readiness. They answer different questions, and pointing both at one path means a slow dependency can trigger restarts instead of just pausing traffic.
RememberRemoving a pod from a Service takes a moment to spread to every node, so a pod that exits instantly can still receive a few requests. Keep serving during a
preStoppause, fail readiness onSIGTERM, and setterminationGracePeriodSecondslonger than your pause plus request draining.
- Be careful with dependency checks in readiness. If readiness checks a shared database, a database blip marks every pod unready at once and removes all capacity. Check what this pod needs to serve, such as warmed caches and initial connections, and cache any dependency check so probes do not hammer it.
- Use a startup probe instead of a long
initialDelaySeconds. A large initial delay slows every restart, while a startup probe waits only as long as the application actually needs. - Do not set aggressive timeouts. A one-second timeout with CPU throttling or a garbage collection pause causes false failures, and false liveness failures cause restart loops.
- Listen on all interfaces. Probes arrive from the node, so an application bound only to
localhostfails every HTTP probe. - Keep probe endpoints fast and unauthenticated. Probes do not follow login flows, and a redirect to a login page can look like a failure.
- Limit exec probes. Each check starts a process inside the container, which adds up on busy nodes, so prefer HTTP, TCP or gRPC.
- Pair probes with a PodDisruptionBudget. Probes protect against bad pods, while a budget protects capacity during node drains and upgrades.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
kubectl describe pod POD |
Show probe configuration and failure events |
kubectl get pod POD -w |
Watch readiness and restarts change |
kubectl get endpoints SERVICE |
See which pod addresses receive traffic |
kubectl rollout status deployment/NAME |
Wait for a rollout and detect a stall |
kubectl rollout undo deployment/NAME |
Return to the previous version |
kubectl logs POD --previous |
Read logs from a container killed by liveness |
| Problem | Cause | Fix |
|---|---|---|
| Pod restarts repeatedly right after start | Liveness runs before the app is up | Add a startup probe |
Readiness probe failed and pod stays 0/1 |
Endpoint returns non-2xx or is unreachable | Test the path from inside the pod |
| All pods unready during a dependency outage | Readiness checks a shared dependency | Check only local state, or degrade gracefully |
| Errors during rollouts despite probes | Pod exits before endpoint removal spreads | Add a preStop pause and fail readiness on SIGTERM |
connection refused on probes |
App listens only on localhost |
Bind to 0.0.0.0 |
| Rollout stalls | New pods never become ready | Check kubectl rollout status and pod events, then undo |