71

The best source for restart policies in Kubernetes I have found is this:

http://kubernetes.io/docs/user-guide/pods/multi-container/#restartpolicy

But it only lists the possible restartPolicy values and does not explain them.

What is the difference between Always and OnFailure? Mustn't the thing fail before it can be restarted?

Opal
  • 81,889
  • 28
  • 189
  • 210
jonalv
  • 5,706
  • 9
  • 45
  • 64

1 Answers1

101

Always means that the container will be restarted even if it exited with a zero exit code (i.e. successfully). This is useful when you don't care why the container exited, you just want to make sure that it is always running (e.g. a web server). This is the default.

OnFailure means that the container will only be restarted if it exited with a non-zero exit code (i.e. something went wrong). This is useful when you want accomplish a certain task with the pod, and ensure that it completes successfully - if it doesn't it will be restarted until it does.

Never means that the container will not be restarted regardless of why it exited.

These different restart policies basically map to the different controller types as you can see from kubectl run --help:

--restart="Always": The restart policy for this Pod. Legal values [Always, OnFailure, Never]. If set to 'Always' a deployment is created for this pod, if set to 'OnFailure', a job is created for this pod, if set to 'Never', a regular pod is created. For the latter two --replicas must be 1. Default 'Always'

And the pod user-guide:

ReplicationController is only appropriate for pods with RestartPolicy = Always. Job is only appropriate for pods with RestartPolicy equal to OnFailure or Never.

Pixel Elephant
  • 20,649
  • 9
  • 66
  • 83
  • Hello Pixel, can I understand that, If I use RS/deployment to create pods, I must set "RestartPolicy = Always" in yaml? – James Pei Apr 10 '20 at 02:41
  • 1
    @JamesPei not really!!. There is nothing to set *RestartPolicy=_something_*. It is an imperative command. All you need to do is you need to create a separate resource like RS or Deployment in your resource-definition file. – Gupta Apr 25 '20 at 09:52
  • When would a container with a web-server exit with a zero exit code? Are there any scenarios where this could happen? – rahulmohan Jan 12 '21 at 18:33
  • Thanks for this explanation, simplier than the official documentation. – d3vpasha May 06 '21 at 20:06
  • 2
    Update: "If set to 'Always' a deployment is created for this pod, if set to 'OnFailure', a job is created for this pod, if set to 'Never', a regular pod is created. For the latter two --replicas must be 1. Default 'Always'" This is not shown anymore in current kubernetes version 1.21 and is no longer valid. Deleting a pod that has set restart Always won't get brought back like a deployment, for example. – somenickname Sep 08 '21 at 18:03