我已经阅读了有关Docker-compose 文档 的容器重启策略,但是我不理解
什么情况下会使用其中一个而不是另一个?在哪些情况下,某种策略会导致启动容器,而另一种策略则不会?
on-failure
和unless-stopped
之间的区别。什么情况下会使用其中一个而不是另一个?在哪些情况下,某种策略会导致启动容器,而另一种策略则不会?
on-failure
和unless-stopped
之间的区别。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重启策略可以保证容器在所有可能的故障中保持活跃,我们可以多种方式利用它,例如,如果我们在容器上运行Web服务器并且需要即使在错误请求时也保持其活动状态,则可以使用unless-stopped
标志,它将使服务器保持运行状态,直到我们手动停止它。
重启标志可以是以下任一标志:
"no"
:默认值,永远不会重新启动容器。on-failure
:每当遇到错误时,即容器内运行的进程以非零退出代码退出时,它都会重新启动容器。退出代码:0表示没有错误,我们有意终止了进程,但任何非零值都是错误。always
:始终重新启动容器,无论退出代码如何。此外,即使我们手动停止了容器,它也会重新启动容器,但需要重新启动Docker守护程序。unless-stopped
:与always
标志类似,唯一的区别是一旦手动停止容器,即使重启Docker守护程序,它也不会自动重新启动,直到我们再次手动启动容器。unless-stopped
和on-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.
docker run --restart on-failure hello-world
的示例,但它并不像那样工作。容器以 0 状态退出并停止运行,它在docker ps
中也没有列出。只有使用--restart always
才能保持 hello-world 容器的运行。为什么会这样呢? - Alexey Grinko