Skip to content
LF Cert Trainer

Lesson 56 · Section 5: Application Lifecycle Management

Lesson 56: Self-healing applications: three layers that repair your Pods

How Kubernetes repairs an application without you: the kubelet restarts containers, controllers replace Pods, the node controller moves work off dead nodes, and probes tell them all what healthy means. · 18 min read · 4 min video

1/10Self-healing applications
0:00 / 3:39

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why self-healing exists

Things fail all the time in a cluster. A process runs out of memory and is killed. An application deadlocks and stops answering while its process is still there. Someone deletes the wrong Pod. A node loses power. With plain containers on plain servers, each of these means a person has to notice and start something again by hand.

Kubernetes takes that job over. You state what should be running, and several independent components keep comparing that with what really runs and repair the difference. That is all "self-healing" means: it is not one feature you switch on, but the normal result of how Kubernetes works.

What it is: three layers of repair

Three layers of self-healingrestartsreplacesevicts Podskubeleton the Pod's nodeContainer exitsor fails livenessReplicaSet ctrlcounts the PodsPod is gonedeleted or evictedNode controllerwatches heartbeatsNode is downNotReady
Three layers of self-healing. Each failure is repaired by a different component. A bare Pod only gets the first layer.

Parts:

  • kubelet (on the Pod's node)
  • Container exits (or fails liveness)
  • ReplicaSet ctrl (counts the Pods)
  • Pod is gone (deleted or evicted)
  • Node controller (watches heartbeats)
  • Node is down (NotReady)

Connections:

  • kubelet to Container exits: restarts
  • ReplicaSet ctrl to Pod is gone: replaces
  • Node controller to Node is down: evicts Pods
What failedWho noticesWhat it doesWhat you see
A container exits, or fails its liveness probeThe kubelet on the nodeRestarts the container inside the same PodRESTARTS goes up; Pod name, IP and node stay the same
A Pod is deleted or evictedThe Pod's controller in kube-controller-managerCreates a new Pod from its templateA new Pod name and IP, RESTARTS at 0
A node stops reportingThe node controller in kube-controller-managerTaints the node; Pods are evicted after 5 minutesNode NotReady, old Pods Terminating, new Pods on other nodes

The layers stack. A Pod you created directly (a "bare" Pod) only has the first layer: the kubelet restarts its containers, but if the Pod is deleted or its node dies, nothing brings it back. That is the practical reason to run applications through a Deployment, even with a single replica.

How it works

Layer one: the kubelet restarts containers

When a container's main process exits, the kubelet looks at the Pod's restartPolicy and decides whether to start it again. The field is set once for the Pod and applies to all its containers.

restartPolicyThe container is restarted whenUsed by
Always (default)It exits for any reason, even with exit code 0Deployments, ReplicaSets, DaemonSets, StatefulSets (the only value they accept)
OnFailureIt exits with a non-zero exit codeJobs that should retry in place
NeverNeverJobs that should fail fast, one-off debug Pods

A restart happens in place: same Pod, same node, same IP address, same volumes. Only the container is new, and the RESTARTS column counts how often this has happened.

The kubelet does not restart a crashing container in a tight loop. The first restart is immediate, then it waits 10 seconds, 20, 40 and so on, up to a maximum of 5 minutes. While it is waiting, kubectl get pods shows CrashLoopBackOff. That status is not an error of its own: it means "this container keeps exiting, and I am pausing before the next try". Once a container has run for 10 minutes without a problem, the delay is reset.

Layer two: controllers replace Pods

A Pod is never repaired or moved. When one is gone, its controller creates another from the template. For a Deployment, that is the ReplicaSet controller: it counts the Pods that match its selector, compares the number with spec.replicas and creates or deletes Pods until they agree.

The other workload controllers heal in their own way:

ControllerWhat it keeps true
ReplicaSet (through a Deployment)A fixed number of interchangeable Pods
DaemonSetOne Pod on every matching node
StatefulSetPods with stable names (db-0, db-1); a missing one is recreated with the same name and storage
JobA number of successful completions; failed Pods are retried up to backoffLimit

The replacement Pod has a new name, a new IP address and an empty filesystem. Anything the old Pod kept in its container or in an emptyDir is lost. Clients keep working only because they talk to a Service, which follows the Pods by label and not by address.

Layer three: the node controller evicts Pods from dead nodes

What happens when a node diestaintsran hereone shortcreatesNode worker-1NotReadyNode controllerno heartbeats seenPod web-…-4kq2xevicted after 300 sReplicaSet webwants 3, counts 2Pod web-…-x7p2don worker-2
What happens when a node dies. The Pod on the dead node is not moved. It is evicted after five minutes, and the ReplicaSet creates a new Pod that the scheduler places on a healthy node.

Parts:

  • Node worker-1 (NotReady)
  • Node controller (no heartbeats seen)
  • Pod web-…-4kq2x (evicted after 300 s)
  • ReplicaSet web (wants 3, counts 2)
  • Pod web-…-x7p2d (on worker-2)

Connections:

  • Node controller to Node worker-1: taints
  • Node worker-1 to Pod web-…-4kq2x: ran here
  • Pod web-…-4kq2x to ReplicaSet web: one short
  • ReplicaSet web to Pod web-…-x7p2d: creates

Every kubelet sends heartbeats to the API server. When they stop, the node controller (part of kube-controller-manager) acts in steps:

  1. After a grace period of under a minute, it sets the node's Ready condition to Unknown. kubectl get nodes shows NotReady.
  2. It adds the taint node.kubernetes.io/unreachable with the effect NoExecute (or node.kubernetes.io/not-ready when the kubelet itself reports that it is not ready).
  3. Every Pod carries a toleration for those two taints with tolerationSeconds: 300, added automatically when the Pod was created. So the Pods stay bound to the node for 5 minutes, in case it comes back.
  4. After that the Pods are evicted, which means deleted. The ReplicaSet sees too few Pods and creates replacements, and the scheduler puts them on healthy nodes.

So a Deployment recovers from a dead node on its own, but not instantly: expect a little under six minutes with the defaults. During that time the Service already stops sending traffic to those Pods, because a Pod on a NotReady node is marked not ready.

Under the hood · Why the old Pods show Terminating for so long

Deleting a Pod is a request to its kubelet to stop the containers, and the kubelet on a dead node cannot answer. The old Pods therefore stay in Terminating (older versions showed Unknown) until the node returns or is removed from the cluster. This is harmless for a Deployment, because the ReplicaSet does not count terminating Pods and has already created the replacements.

Two controllers behave differently on purpose:

  • DaemonSet Pods tolerate the two taints without a time limit. They are never evicted: a DaemonSet Pod belongs to its node, and there is nowhere else to run it.
  • StatefulSet Pods are not replaced while the old Pod is still Terminating, because two Pods named db-0 writing to the same volume could corrupt data. If you are sure the node is gone for good, delete the Node object or force-delete the Pod with kubectl delete pod db-0 --grace-period=0 --force.

You can shorten or lengthen the five minutes per Pod by writing the toleration yourself:

tolerations:
  - key: node.kubernetes.io/unreachable
    operator: Exists
    effect: NoExecute
    tolerationSeconds: 30

Probes: telling Kubernetes what healthy means

Without probes, the kubelet knows only one thing about a container: whether its main process is running. That misses two common cases. An application can be running but broken (deadlocked, out of connections), and it can be running but not ready (still loading data, waiting for a database). Probes are checks the kubelet runs against the container to find out.

Three probes, three different consequencesfailsfailsfailskubeletruns the probesstartupProbehas it started yet?livenessProbeis it still working?readinessProbecan it take traffic?Restartnever came upRestartstuck or deadlockedNo trafficout of the Service
Three probes, three different consequences. The kubelet runs every probe from the node. Only the liveness and startup probes ever restart a container.

Parts:

  • kubelet (runs the probes)
  • startupProbe (has it started yet?)
  • livenessProbe (is it still working?)
  • readinessProbe (can it take traffic?)
  • Restart (never came up)
  • Restart (stuck or deadlocked)
  • No traffic (out of the Service)

Connections:

  • kubelet to startupProbe
  • kubelet to livenessProbe
  • kubelet to readinessProbe
  • startupProbe to Restart: fails
  • livenessProbe to Restart: fails
  • readinessProbe to No traffic: fails
ProbeQuestionWhen it failsWithout it
livenessProbeIs the application still working?The kubelet kills the container and restarts it according to restartPolicyOnly a process that exits is restarted
readinessProbeCan it serve requests right now?The Pod is marked not ready and removed from the endpoints of its Services. No restartThe Pod counts as ready the moment its containers start
startupProbeHas it finished starting?The container is killed and restartedLiveness and readiness start checking straight away

While a startup probe has not yet succeeded, the other two probes are switched off. That is its whole purpose: a slow application gets time to start without you having to make the liveness probe slow for the rest of its life.

Each probe uses one of four checks:

CheckSucceeds when
httpGet (path, port)The response status is 200 to 399
tcpSocket (port)The port accepts a connection
exec (command)The command, run inside the container, exits with 0
grpc (port)The gRPC health check answers SERVING

And the same timing fields apply to all of them:

FieldMeaningDefault
initialDelaySecondsWait after the container starts before the first check0
periodSecondsTime between checks10
timeoutSecondsHow long one check may take1
failureThresholdFailures in a row before the probe counts as failed3
successThresholdSuccesses in a row before it counts as passed again (must be 1 for liveness and startup)1

With the defaults, a liveness probe needs three failures ten seconds apart, so a stuck container is restarted after roughly 30 seconds. A startup probe with periodSeconds: 5 and failureThreshold: 30 gives the application 5 × 30 = 150 seconds to come up.

Under the hood · How readiness connects to Services and rollouts

The readiness probe sets the Pod's Ready condition, and two other parts of Kubernetes read that condition:

  • Services. The EndpointSlice controller lists only ready Pods as endpoints that may receive traffic. A Pod that fails readiness keeps running and keeps its IP; it just stops receiving requests through the Service until the probe passes again.
  • Deployments. A rolling update only removes an old Pod once a new Pod is ready. Without a readiness probe a new Pod is "ready" as soon as its process starts, so a version that starts and then fails can replace every healthy Pod. With one, a broken version never becomes ready and the rollout stops while the old Pods keep serving.

So readiness is also a self-healing primitive: it removes a sick Pod from service and puts it back when it recovers, without a restart.

Using it

Example · Watch a controller replace a Pod

Create a Deployment with three replicas, delete one Pod and watch the repair.

kubectl create deployment web --image=nginx:1.29 --replicas=3
kubectl get pods -l app=web -o wide
kubectl delete pod web-5d4f8c7b9d-4kq2x
kubectl get pods -l app=web -o wide
NAME                   READY   STATUS    RESTARTS   AGE   IP            NODE
web-5d4f8c7b9d-9wzjm   1/1     Running   0          9m    10.244.1.12   worker-1
web-5d4f8c7b9d-tb7hn   1/1     Running   0          9m    10.244.2.8    worker-2
web-5d4f8c7b9d-x7p2d   1/1     Running   0          6s    10.244.2.9    worker-2

The replacement has a new name, a new IP, possibly another node, and RESTARTS is 0. It is a new Pod, not a restarted one. The ReplicaSet's events record who made it:

kubectl describe replicaset web-5d4f8c7b9d | tail -3
  Normal  SuccessfulCreate  6s  replicaset-controller  Created pod: web-5d4f8c7b9d-x7p2d

Example · Watch the kubelet restart a container

Kill the main process of one container. In the nginx image, process 1 is nginx itself:

kubectl exec web-5d4f8c7b9d-9wzjm -- /bin/sh -c "kill 1"
kubectl get pod web-5d4f8c7b9d-9wzjm -o wide
NAME                   READY   STATUS    RESTARTS     AGE   IP            NODE
web-5d4f8c7b9d-9wzjm   1/1     Running   1 (4s ago)   12m   10.244.1.12   worker-1

Same name, same IP, same node, and RESTARTS is now 1. This was the kubelet, not the ReplicaSet: from the ReplicaSet's point of view nothing was ever missing.

Example · Add a liveness probe and watch it fire

This Pod creates the file /tmp/healthy, removes it after 30 seconds and keeps running. The process never exits, so without a probe Kubernetes would consider it healthy forever.

apiVersion: v1
kind: Pod
metadata:
  name: liveness-demo
spec:
  containers:
    - name: app
      image: busybox:1.36
      command: ["sh", "-c", "touch /tmp/healthy; sleep 30; rm -f /tmp/healthy; sleep 600"]
      livenessProbe:
        exec:
          command: ["cat", "/tmp/healthy"]
        initialDelaySeconds: 5
        periodSeconds: 5
kubectl apply -f liveness-demo.yaml
kubectl describe pod liveness-demo | tail -6
  Normal   Started    50s               kubelet  Started container app
  Warning  Unhealthy  5s (x3 over 15s)  kubelet  Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
  Normal   Killing    5s                kubelet  Container app failed liveness probe, will be restarted

Three failures five seconds apart (failureThreshold defaults to 3), then the kubelet kills the container and starts a new one. The new container creates the file again, so the cycle repeats and RESTARTS keeps growing.

Example · Add readiness and liveness probes to a Deployment

A task says: "Pods of the Deployment web must only receive traffic when nginx answers on port 80, and must be restarted if it stops answering." kubectl create has no flags for probes, so edit the Deployment:

kubectl edit deployment web
    spec:
      containers:
        - name: nginx
          image: nginx:1.29
          readinessProbe:
            httpGet:
              path: /
              port: 80
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /
              port: 80
            initialDelaySeconds: 10
            periodSeconds: 10

Saving changes the Pod template, so a rollout starts. Finish with the check that proves it worked:

kubectl rollout status deployment/web
kubectl describe deployment web | grep -E "Liveness|Readiness"
    Liveness:   http-get http://:80/ delay=10s timeout=1s period=10s #success=1 #failure=3
    Readiness:  http-get http://:80/ delay=0s timeout=1s period=5s #success=1 #failure=3

Example · Find out why a container keeps restarting

A Pod shows a growing restart count. Three commands give you the cause:

kubectl get pod api-6f7c9d8b5-kx2vq                 # how many restarts, and how recent
kubectl describe pod api-6f7c9d8b5-kx2vq            # Last State, exit code, events
kubectl logs api-6f7c9d8b5-kx2vq --previous         # what the container said before it died

In describe, read the Last State block of the container and then the events:

What you findWhat it means
Reason: OOMKilled, exit code 137The container went over its memory limit. Raise the limit or fix the leak
Reason: Error, exit code 1 (or another small number)The application exited by itself. The cause is in logs --previous
Reason: Completed, exit code 0The command finished. With restartPolicy: Always it is restarted anyway: the command is wrong for a long-running Pod
Event Liveness probe failed, then KillingThe probe restarted it. Check the probe's path, port and timing before blaming the application
Event Readiness probe failed, no restarts, READY 0/1The Pod runs but gets no traffic. Check the probe's path and port

Tricks

Common mistakes

  • Expecting a bare Pod to come back. The kubelet restarts its containers, but a deleted Pod, or one on a node that died, is gone. Use a Deployment.
  • Reading CrashLoopBackOff as the problem. It is the kubelet waiting between restarts. The problem is whatever makes the container exit: look at kubectl logs --previous and the exit code.
  • Mixing up liveness and readiness. Liveness restarts the container. Readiness only stops traffic. Using a liveness probe for "the database is slow" restarts healthy Pods for nothing.
  • A probe on the wrong port or path. With a wrong liveness probe the container restarts forever; with a wrong readiness probe the Pod never receives traffic. The events in kubectl describe pod name the probe that failed.
  • No start-up time for a slow application. If the liveness probe starts before the application is up, the container is killed before it ever becomes healthy. Add a startupProbe, or at least initialDelaySeconds.
  • Expecting instant recovery from a dead node. Pods wait about five minutes before they are evicted. Until then the Deployment runs with fewer ready Pods.
  • Thinking self-healing fixes the cause. A restart clears a stuck process, not a bad image, a missing ConfigMap or a wrong command. Those loop until you fix the Pod template.

Recap

  • A container that exits or fails its liveness probe is restarted in place by the kubelet, according to restartPolicy (default Always), with a growing back-off shown as CrashLoopBackOff.
  • A Pod that is gone is replaced by its controller with a new Pod: new name, new IP. Bare Pods are not replaced.
  • Pods on a dead node are evicted after 5 minutes (tolerationSeconds: 300) and recreated on healthy nodes.
  • Probes define health: liveness restarts, readiness removes from Service endpoints, startup holds the other two back for slow applications.
  • To read a repair: RESTARTS, kubectl describe pod (Last State, exit code, events) and kubectl logs --previous.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Add a liveness probe so that a hung copy is restarted by itself, and a readiness probe so that a warming-up copy gets no traffic.

    Build · Level 2 · standard · target 15 min

  • Section capstone. One Deployment, five jobs: get it past a broken init container, feed it from a ConfigMap and a Secret, add probes, release a new version with no gap, and prepare it for autoscaling.

    Fix · Level 3 · challenge · target 30 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.