Kubernetes is a declarative system: we tell it the state we want, such as "this service should have 3 Pods running", and its components keep comparing that with the actual state and fix any difference they find. Self-healing is simply this compare-and-fix process.

It isn't a single feature. Different components handle it at different layers:

Layer Component What happens How it's fixed
Container kubelet Container crashes, liveness probe fails Restart the container in the same Pod
Traffic kubelet + EndpointSlice controller Readiness probe fails Temporarily remove the Pod from the Service, no restart
Pod ReplicaSet controller Pod is deleted or evicted Create a new Pod to restore the count
Node Node lifecycle controller Node is unreachable or NotReady Evict the Pods; the ReplicaSet recreates them on other Nodes

The easiest thing to mix up is the difference between the first two layers and the last two: a container restart is done by the kubelet on the original Node, and the Pod stays the same; a Pod replacement is done by a controller, and the new Pod gets a new name, a new IP, and possibly a different Node.


Container Layer: restartPolicy

When a container's main process exits (whether cleanly or by crashing), the kubelet uses the Pod's spec.restartPolicy to decide whether to restart it:

restartPolicy Behavior Typical use
Always (default) Restart regardless of exit code Long-running services; the only value a Deployment allows
OnFailure Restart only on a non-zero exit code Jobs
Never Never restart One-off debug Pods, Jobs

restartPolicy is set at the Pod level and applies to every container in the Pod.

CrashLoopBackOff

If a container dies right after starting, the kubelet doesn't restart it endlessly as fast as it can. It uses exponential backoff: 10 seconds, 20, 40, and so on, capped at 5 minutes. Once a container runs for 10 minutes without problems, the delay resets.

While it is waiting for the next restart, kubectl get pods shows CrashLoopBackOff:

kubectl run crash --image=busybox:1.36 -- sh -c "echo boom; exit 1"
kubectl get pod crash -w
NAME    READY   STATUS             RESTARTS      AGE
crash   0/1     CrashLoopBackOff   3 (30s ago)   80s

RESTARTS keeps going up, but the Pod name and AGE don't change, which means it's the container inside the same Pod being restarted. To find out why, look at the logs of the previous container:

kubectl logs crash --previous
kubectl describe pod crash   # check the Exit Code and Reason under Last State

CrashLoopBackOff is not the root cause

CrashLoopBackOff only means "the container keeps dying and the kubelet is waiting to restart it again". The real cause is in the --previous logs or the Exit Code in describe; for example, 137 usually means it was OOMKilled.


Container Layer: Probes

restartPolicy only handles the case where the process exits. If the process is still alive but hung and no longer answering requests, the kubelet sees a running container and does nothing. That's what probes are for: they let the kubelet actively check whether a container is healthy.

The Three Probes

Probe Action on failure Purpose
livenessProbe Kill the container, then restart it according to restartPolicy Detect hangs and deadlocks
readinessProbe Remove the Pod from the Service endpoints, no restart Don't send traffic while not ready or temporarily overloaded
startupProbe Liveness and readiness don't run until it succeeds; too many failures kill the container Slow-starting apps, so liveness doesn't kill them before they finish starting

There are four check types: httpGet (a 200–399 response is success), tcpSocket (success if a connection can be opened), exec (success if the command exits with 0), and grpc.

Common fields:

Field Default Description
initialDelaySeconds 0 How long to wait after the container starts before probing
periodSeconds 10 How often to probe
timeoutSeconds 1 Timeout for a single probe
failureThreshold 3 Consecutive failures before the probe counts as failed
successThreshold 1 Consecutive successes to count as recovered (must be 1 for liveness and startup)

Hands-on: A Failing Liveness Probe Triggers a Restart

This example comes from the official docs. The container creates /tmp/healthy at startup and deletes it 30 seconds later, simulating an app that breaks after running for a while:

apiVersion: v1
kind: Pod
metadata:
  name: liveness-exec
spec:
  containers:
  - name: liveness
    image: busybox:1.36
    args:
    - /bin/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-exec.yaml
kubectl get pod liveness-exec -w

For the first 30 seconds cat /tmp/healthy succeeds. After the file is deleted, the probe fails 3 times in a row (about 15 seconds), then the kubelet kills and restarts the container, and RESTARTS becomes 1. describe shows the whole sequence in Events:

kubectl describe pod liveness-exec
Warning  Unhealthy  ...  Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
Normal   Killing    ...  Container liveness failed liveness probe, will be restarted

The HTTP Version

Real web services usually use httpGet and set both readiness and liveness:

containers:
- name: web
  image: nginx:1.29
  ports:
  - containerPort: 80
  readinessProbe:
    httpGet:
      path: /
      port: 80
    periodSeconds: 5
  livenessProbe:
    httpGet:
      path: /
      port: 80
    initialDelaySeconds: 10
    periodSeconds: 10

Don't check external dependencies in a liveness probe

If the liveness probe checks whether the database is reachable, then when the database goes down every Pod gets restarted together. Restarting doesn't fix the database; it only makes things worse. Liveness should only check that this process itself is alive; leave "temporarily unable to serve" to readiness.


Pod Layer: ReplicaSet

Everything so far is the kubelet restarting containers inside an existing Pod. But if the Pod itself is gone, because it was deleted, evicted, or its Node died, the kubelet can't help, since nothing remembers that "a Pod should be here".

The core job of a ReplicaSet is to keep a specified number of identical Pods running, so the service stays highly available. The ReplicaSet controller in kube-controller-manager keeps checking:

  • How many Pods currently match the selector.
  • If there are fewer than replicas, create new Pods from the template.
  • If there are more than replicas, delete the extras.

How to Use a ReplicaSet

The official docs recommend the following in practice:

  • Don't manage it directly: don't write your own ReplicaSet YAML to create and modify ReplicaSet objects (kubectl create doesn't even have a subcommand for ReplicaSets).

  • Use a Deployment instead: just define a Deployment. Kubernetes creates and maintains the ReplicaSet underneath for you, and adds rolling updates and rollbacks on top.

How Deployments, ReplicaSets and Pods relate, and how rolling updates work, is covered in detail in Workloads and Scheduling. Here we create a ReplicaSet directly anyway, to watch how it behaves on its own:

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: frontend
  labels:
    app: guestbook
    tier: frontend
spec:
  # modify replicas according to your case
  replicas: 3
  selector:
    matchLabels:
      tier: frontend
  template:
    metadata:
      labels:
        tier: frontend
    spec:
      containers:
      - name: php-redis
        image: us-docker.pkg.dev/google-samples/containers/gke/gb-frontend:v5

template.metadata.labels must match the selector, or the API server rejects it.

kubectl apply -f frontend.yaml
kubectl get rs frontend
kubectl get pods -l tier=frontend -o wide

Hands-on: Delete a Pod

# watch in another terminal
kubectl get pods -l tier=frontend -w

# delete one of the Pods
kubectl delete pod <name of one frontend Pod>

As soon as the deleted Pod goes into Terminating, a Pod with a new name starts being created. This is different from a container restart: the new Pod has RESTARTS at 0, its AGE starts from zero, and its IP changes.

kubectl describe rs frontend
Events:
  Normal  SuccessfulCreate  ...  Created pod: frontend-xxxxx

How a ReplicaSet Recognizes Its Pods

A ReplicaSet finds Pods through its label selector, not by whether it created them. Look at a Pod with -o yaml and you'll see metadata.ownerReferences pointing to the ReplicaSet:

kubectl get pod <frontend Pod name> -o jsonpath='{.metadata.ownerReferences[0].kind}/{.metadata.ownerReferences[0].name}{"\n"}'
# ReplicaSet/frontend

This leads to a behavior that's easy to trip over: any Pod whose labels match the selector and that has no other owner gets adopted by the ReplicaSet. Try creating a Pod with tier: frontend by hand:

kubectl run stray --image=nginx:1.29 --labels=tier=frontend
kubectl get pods -l tier=frontend

stray is deleted right after it's created: the ReplicaSet adopts it, finds 4 Pods, which is more than replicas: 3. It works the other way too. Change a Pod's label and it leaves the ReplicaSet; the ReplicaSet creates a replacement, and the original Pod stays behind as a standalone Pod you can use for debugging:

kubectl label pod <frontend Pod name> tier=debug --overwrite
kubectl get pods --show-labels

Scaling and Deleting

# change the replica count
kubectl scale rs frontend --replicas=5

# delete the ReplicaSet together with its Pods
kubectl delete rs frontend

# delete only the ReplicaSet and keep the Pods
kubectl delete rs frontend --cascade=orphan

Editing the template doesn't touch existing Pods

If you edit a ReplicaSet's template directly (for example, change the image), Pods that are already running are not updated; only Pods created afterwards use the new template. This is one more reason to use a Deployment: rolling updates only exist in Deployments.


ReplicationController

ReplicationController is the predecessor of ReplicaSet and does almost the same thing: keep a specified number of Pods running. The official recommendation today is to use a Deployment (with a ReplicaSet underneath). The main difference between the two is the selector:

ReplicationController ReplicaSet
API version v1 apps/v1
selector Equality-based only (tier: frontend) Also supports set-based matchExpressions (In, NotIn, Exists, DoesNotExist)
If selector is omitted Defaults to the template's labels Required
Rolling updates Used to rely on kubectl rolling-update, which has been removed Handled by Deployments
apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.29

The selector is written directly as key/value pairs with no matchLabels level, which is the most visible difference from ReplicaSet YAML. A set-based selector looks like this, and it's something a ReplicationController can't do:

selector:
  matchExpressions:
  - key: tier
    operator: In
    values: [frontend, web]

Unless you're maintaining old manifests, it's enough to recognize a ReplicationController when you see one. New services should always use a Deployment.


Node Layer: What Happens When a Node Fails

When a Node shuts down, loses its network, or its kubelet stops reporting, self-healing goes like this:

  1. The kubelet stops renewing the Node's heartbeat (Lease). After node-monitor-grace-period, the Node lifecycle controller marks the Node NotReady or Unknown.
  2. The Node gets a node.kubernetes.io/not-ready or node.kubernetes.io/unreachable taint with the NoExecute effect.
  3. Pods have default tolerations for both taints with a 300-second limit, so they stay put for 5 minutes first. This keeps a brief network blip from causing mass rescheduling.
  4. After 300 seconds the Pods are evicted. The ReplicaSet sees fewer available Pods and creates new ones on other healthy Nodes.

You can watch this directly on a three-node cluster (k8s-cp1, k8s-w1, k8s-w2):

kubectl create deployment web --image=nginx:1.29 --replicas=4
kubectl get pods -l app=web -o wide

# on k8s-w1, stop the kubelet to simulate a lost Node
sudo systemctl stop kubelet

# back on the control plane, watch
kubectl get nodes -w
kubectl get pods -l app=web -o wide -w

Within about a minute k8s-w1 turns NotReady. Five minutes later, the Pods that were on k8s-w1 become Terminating and new Pods appear on k8s-w2. Because the kubelet is stopped, the old Pods can't finish deleting and stay in Terminating until the kubelet comes back:

# on k8s-w1, bring it back
sudo systemctl start kubelet

You can see each Pod's default tolerations like this:

kubectl get pod <web Pod name> -o jsonpath='{.spec.tolerations}' | jq
[
  { "effect": "NoExecute", "key": "node.kubernetes.io/not-ready", "operator": "Exists", "tolerationSeconds": 300 },
  { "effect": "NoExecute", "key": "node.kubernetes.io/unreachable", "operator": "Exists", "tolerationSeconds": 300 }
]

If you want Pods to move off a failed Node faster, define these two tolerations on the Pod yourself with a smaller tolerationSeconds.

Pods without a controller are not recreated

A Pod created directly with kubectl run and not managed by any controller (a bare Pod) is simply gone after it's evicted or its Node dies; it won't be recreated on another Node. Any service that needs self-healing must be managed by a controller such as a Deployment or StatefulSet.


What I Ran Into on a Real Project

I've hit every layer above on a project at work (Spring Boot microservices on an RKE2 cluster). Here are a few of the more representative cases.

A Liveness Probe Taken Down by the Mail Server

At first, every Spring Boot service pointed both liveness and readiness at the same /actuator/health. That endpoint aggregates every auto-configured health indicator, and any project that uses JavaMailSender gets a MailHealthIndicator, which actually connects to SMTP on every check.

One day the mail server in the test environment slowed down, the health check went over timeoutSeconds, liveness failed several times in a row, and the kubelet kept restarting every service that sends mail. The services themselves were fine; only the mail server was slow, yet they all went down. That's exactly the situation in the WARNING above.

The immediate fix was to turn off the mail check:

management:
  health:
    mail:
      enabled: false

But the root problem is that /actuator/health also checks the DB and Redis by default, so if the database stalls, liveness restarts every backend at once. The better approach is to split the two probes; Spring Boot already provides an endpoint for each:

livenessProbe:
  httpGet:
    path: /actuator/health/liveness    # only the process's own state
    port: 8080
readinessProbe:
  httpGet:
    path: /actuator/health/readiness   # dependencies like DB and Redis go here
    port: 8080

The Cause of CrashLoopBackOff Was Somewhere Else

One day several services went into CrashLoopBackOff at the same time. It looked like a code problem, but kubectl logs --previous showed they couldn't reach object storage (MinIO) at startup. Digging further, the MinIO Pod was stuck in ImagePullBackOff because Docker Hub had rate-limited the pulls.

The chain was: image can't be pulled → MinIO doesn't start → services fail to create their bucket at startup → the Spring context doesn't start → CrashLoopBackOff. This case shows two things:

  • CrashLoopBackOff is only the symptom; trace the real cause back from the --previous logs.
  • Requiring an external dependency to be available at startup ties that dependency's state to the container's lifecycle, and no number of kubelet restarts will fix it.

Single Replica + RWO PVC + RollingUpdate Deadlock

One service had a single replica, a ReadWriteOnce PVC, and the default RollingUpdate strategy. On a rollout, the Deployment creates the new Pod first and deletes the old one only once the new one is Ready. But the new Pod was scheduled on a different Node while the volume was still attached to the old Pod's Node, so it got stuck at:

Warning  FailedAttachVolume  Multi-Attach error for volume "pvc-xxxx" Volume is already used by pod(s) ...

The old Pod waits for the new one to be Ready before it's deleted, and the new Pod waits for the old one to release the volume before it can start. The Deployment never converges, and the only way out was to scale to 0 and back to 1 by hand. This is the controller's replace-a-Pod mechanism running into a storage limitation, and self-healing itself gets stuck.

There are two ways out:

  • For something stateful that can only run one replica, use strategy.type: Recreate, which deletes the old Pod before creating the new one, at the cost of a brief outage on every rollout.
  • Move the state out. This service later moved its attachments to object storage, so the Pod no longer needed a PVC and could do normal rolling updates and run multiple replicas.

A Node Died and We Waited 5 Minutes

Once, a Node was marked NotReady. The backend services all had 2 replicas, so they were mostly fine, but key components such as Redis, the database operator and the MetalLB controller had only 1 replica each, and they all happened to be on that Node.

What followed matched the description above exactly: the Pods stayed put for 300 seconds because of the default tolerations before being evicted, and the service was almost completely down for those 5 minutes. Changes made afterwards:

  • The traffic entry point came first: the gateway Pods were spread across Nodes with topologySpreadConstraints, and their toleration wait was shortened.
  • The other key components need the same treatment (multiple replicas spread across Nodes); that work is still in progress.
tolerations:
- key: node.kubernetes.io/unreachable
  operator: Exists
  effect: NoExecute
  tolerationSeconds: 30
- key: node.kubernetes.io/not-ready
  operator: Exists
  effect: NoExecute
  tolerationSeconds: 30

Self-healing only works when there's somewhere left to heal to. A single-replica component, even one managed by a controller, still has to wait for eviction and then for recreation when its Node dies, and the service is down for that whole time.


Summary

  • Self-healing comes from Kubernetes constantly pulling the actual state back to the desired state, with different components responsible at different layers.
  • The kubelet restarts containers in the same Pod according to restartPolicy; repeated failures lead to CrashLoopBackOff, and kubectl logs --previous shows why.
  • A failing livenessProbe restarts the container, a failing readinessProbe only stops traffic, and a startupProbe gives slow-starting apps time to come up.
  • A ReplicaSet keeps the Pod count through its label selector and creates new Pods when one is deleted; Pods with matching labels get adopted.
  • ReplicationController is the older ReplicaSet and only supports equality-based selectors; in practice you use neither directly and use a Deployment instead.
  • When a Node fails, Pods wait 300 seconds by default before being evicted, then a controller recreates them on other Nodes; bare Pods are not recreated.

References

  1. ReplicaSetkubernetes.io
  2. ReplicationControllerkubernetes.io
  3. Kubernetes Self-Healingkubernetes.io
  4. Pod Lifecyclekubernetes.io
  5. Configure Liveness, Readiness and Startup Probeskubernetes.io
  6. Taints and Tolerationskubernetes.io