【问题标题】:Difference in docker restart policy between on-failure and unless-stopped?失败时和除非停止时 docker 重启策略的区别?
【发布时间】:2020-08-26 17:28:22
【问题描述】:

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

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

【问题讨论】:

    标签: docker docker-compose restart keep-alive


    【解决方案1】:

    如果退出代码指示失败,on-failure 将发出重新启动,而 unless-stopped 的行为类似于 always 并将保持实例运行,除非容器停止。

    你可以试试 hello-world 看看有什么不同。

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

    不过,docker run --restart unless-stopped hello-world 会在容器成功退出的情况下重新启动,因此随后运行 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 run --restart on-failure hello-world 尝试了这个例子,但它不是那样工作的。容器以 0 状态退出并停止,它未在 docker ps 中列出。只有使用 --restart always 运行才能保持 hello-world 容器运行。这是为什么呢?
    • @AlexeyGrinko 这正是这个答案中所说的
    【解决方案2】:

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

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

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

    一旦容器停止,它的重启标志就会被忽略,这是克服重启循环的一种方法。这就是为什么在 always flag 的情况下,一旦我们手动停止它,容器将不会重新启动,直到我们重新启动 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.
    

    【讨论】:

      猜你喜欢
      • 2018-06-02
      • 2015-04-30
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      相关资源
      最近更新 更多