Tag Archives: always

How to Set `restartPolicy` in Kubernetes: Examples and Usage

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: v1
kind: Pod
metadata:
name: always-pod
spec:
restartPolicy: Always
containers:
- name: nginx
image: nginx

Command to deploy:

kubectl apply -f always.yaml
kubectl get pods

Behavior:

  • Even if container stops β†’ it will restart again and again

Example 2: restartPolicy = OnFailure

apiVersion: v1
kind: Pod
metadata:
name: fail-pod
spec:
restartPolicy: OnFailure
containers:
- name: test
image: busybox
command: ["sh", "-c", "exit 1"]

Command:

kubectl apply -f onfailure.yaml
kubectl get pods

Behavior:

  • exit 1 β†’ restart
  • exit 0 β†’ no restart

Example 3: restartPolicy = Never

apiVersion: v1
kind: Pod
metadata:
name: never-pod
spec:
restartPolicy: Never
containers:
- name: test
image: busybox
command: ["sh", "-c", "echo Hello && exit 0"]

Command:

kubectl apply -f never.yaml
kubectl get pods

Behavior:

  • Runs once β†’ stops β†’ no restart

Quick kubectl command

-- Always
kubectl run test --image=nginx --restart=Always
-- OnFailure
kubectl run test --image=busybox --restart=OnFailure -- /bin/sh -c "exit 1"
-- Never
kubectl run test --image=busybox --restart=Never -- echo Hello

How to check restartPolicy

kubectl get pod <pod-name> -o yaml | grep restartPolicy