What is restartPolicy in Kubernetes
restartPolicy tells Kubernetes:
π βWhat should I do when a container inside a Pod stops?β
Kubernetes uses this for self-healing (auto restart).
Types of restartPolicy
There are 3 values only:
1. Always (default)
- Container will restart every time it stops
- Even if it exited successfully β
π Used for:
- Web apps
- APIs
- Long running services
2. OnFailure
- Restart only if error happens (exit code β 0)
- No restart if success
π Used for:
- Batch jobs
- Data processing
3. Never
- Never restart
π Used for:
- One-time scripts
- Migration jobs
Where to write restartPolicy
spec: restartPolicy: Always | OnFailure | Never
Example 1: restartPolicy = Always
apiVersion: v1kind: Podmetadata: name: always-podspec: restartPolicy: Always containers: - name: nginx image: nginx
Command to deploy:
kubectl apply -f always.yamlkubectl get pods
Behavior:
- Even if container stops β it will restart again and again
Example 2: restartPolicy = OnFailure
apiVersion: v1kind: Podmetadata: name: fail-podspec: restartPolicy: OnFailure containers: - name: test image: busybox command: ["sh", "-c", "exit 1"]
Command:
kubectl apply -f onfailure.yamlkubectl get pods
Behavior:
- exit 1 β restart
- exit 0 β no restart
Example 3: restartPolicy = Never
apiVersion: v1kind: Podmetadata: name: never-podspec: restartPolicy: Never containers: - name: test image: busybox command: ["sh", "-c", "echo Hello && exit 0"]
Command:
kubectl apply -f never.yamlkubectl get pods
Behavior:
- Runs once β stops β no restart
Quick kubectl command
-- Alwayskubectl run test --image=nginx --restart=Always-- OnFailurekubectl run test --image=busybox --restart=OnFailure -- /bin/sh -c "exit 1"-- Neverkubectl run test --image=busybox --restart=Never -- echo Hello
How to check restartPolicy
kubectl get pod <pod-name> -o yaml | grep restartPolicy