docker 失败时重启策略和除非停止时重启策略的区别?

Difference in docker restart policy between on-failure and unless-stopped?

我已经阅读了 docker-compose documentation 关于容器的重启策略, 但是我没能理解 on-failureunless-stopped 之间的区别。

我什么时候会用一个代替另一个?在哪些情况下某个策略会导致启动容器而另一个策略不会?

如果退出代码指示失败,

on-failure 将发出重新启动,而 unless-stopped 的行为类似于 always 并且将保留实例 运行ning 除非容器是停止了。

您可以尝试使用 hello-world 来查看差异。

docker run --restart on-failure hello-world 将 运行 一次并成功退出,并且 运行ning 后续 docker ps 将指示当前没有 运行ning 容器实例。

但是,即使容器成功退出,docker run --restart unless-stopped hello-world 也会重新启动容器,因此随后 运行ning docker ps 将向您显示一个重新启动的实例,直到您停止容器。

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                                  PORTS               NAMES
4d498ebd13a6        hello-world         "/hello"            2 seconds ago       Restarting (0) Less than a second ago                       modest_keldysh

Docker 重启策略是为了让容器在所有可能的崩溃中保持活动状态,我们可以通过多种方式利用它作为示例,如果我们在容器上有一个 Web 服务器 运行 并且必须即使在错误的请求下也保持活动状态我们可以使用 unless-stopped 标志,它将保持服务器正常运行并 运行 直到我们手动停止它。

重新启动标志可以是以下任何一个:-

  1. "no" :- 这是默认值,永远不会重启容器。
  2. on-failure :- 它会在遇到错误时重新启动容器,或者说,每当容器内的进程 运行 以非零退出代码退出时。退出代码:- 0 表示没有错误,我们有意终止了进程,但任何非零值都是错误。
  3. always :- 正如名称一样,它总是会重启容器,无论退出代码是什么。此外,即使我们手动停止它,它也会重新启动容器,但为此我们需要重新启动 docker 守护进程。
  4. unless-stopped :- 它类似于 always 标志,唯一的区别是一旦手动停止容器,即使在重新启动 docker 守护程序后它也不会自动重新启动,直到我们再次手动启动容器。

unless-stoppedon-failure 之间的区别是第一个将始终重新启动,直到我们手动停止它,无论退出代码是什么,另一个只会在真正失败时重新启动容器,即退出代码 = 非零。

容器停止后,其重启标志将被忽略,这是克服重启循环的一种方法。这就是为什么在 always 标志的情况下,一旦我们手动停止它,容器将不会重新启动,直到我们重新启动 docker 守护进程。

您可以通过创建一个简单的 redis-server:

轻松测试所有这些标志
 docker run -d --restart=always --name redis-server redis  # start redis image
 docker container ls # test the status 
 docker stop redis-server # stop the container manually
 docker container ls # test the status again, got the redis-server did not restarted 
 sudo service docker restart # restart the docker daemon 
 # test the status again will find the container is again up and running
 # try the same steps by changing the restart flag with *unless-stopped*
 docker update --restart=unless-stopped redis-server # will update the restart flag of running container.