【发布时间】:2020-08-26 17:28:22
【问题描述】:
我已经阅读了关于容器重启策略的 docker-compose documentation,
但是我不明白on-failure 和unless-stopped 之间的区别。
我什么时候会使用其中一种?在哪些情况下某个策略会导致启动容器而另一个策略不会?
【问题讨论】:
标签: docker docker-compose restart keep-alive
我已经阅读了关于容器重启策略的 docker-compose documentation,
但是我不明白on-failure 和unless-stopped 之间的区别。
我什么时候会使用其中一种?在哪些情况下某个策略会导致启动容器而另一个策略不会?
【问题讨论】:
标签: docker docker-compose restart keep-alive
如果退出代码指示失败,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 容器运行。这是为什么呢?
docker restart 策略可以让容器在所有可能的故障中保持活动状态,我们可以通过多种方式利用它,例如,如果我们有一个在容器上运行的 Web 服务器并且即使在出现错误请求时也必须保持它的活动状态,我们可以使用 unless-stopped 标志,它将保持服务器正常运行,直到我们手动停止它。 重启标志可以是以下任何一种:-
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.
【讨论】: