假设我有一个想要运行的Docker容器,然后我可以调用它

$ docker run ...

一切都很好。是否有一种内置的方法来运行容器,使其在系统崩溃并重新启动时自动重新启动?

如果是的话,这在Docker Compose中也可用吗?


当前回答

文档中的更“温和”模式:

docker run -dit --restart unless-stopped <image_name>

其他回答

你可以运行一个总是重启的容器:

$ docker run -dit --restart unless-stopped <image name OR image hash>

如果你想改变一个正在运行的容器的配置,你应该通过以下方式更新它:

$ docker update --restart=<options> <container ID OR name>

如果你想查看容器的当前策略,首先执行下面的命令:

docker inspect gateway | grep RestartPolicy -A 3

毕竟,不要忘记在系统引导时启用已安装的docker守护进程:

$ systemctl enable docker

要查看重启策略的完整列表,请参见:重启策略

你可以使用docker update——restart=on-failure <容器ID或名称>。

顾名思义,On -failure不仅会在失败时重新启动容器,还会在系统引导时重新启动容器。

根据文档,有多个重启选项:

Flag            Description
no              Do not automatically restart the container. (the default)
on-failure      Restart the container if it exits due to an error, which manifests as a non-zero exit code.
always          Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details)
unless-stopped  Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.

这就是crontab的作用:

@reboot sleep 10 ; docker start <container name> 2>&1 | /usr/bin/logger -t 'docker start'

通过crontab -e访问用户crontab或使用crontab -l显示它或在/etc/crontab编辑系统crontab

这个答案只能作为备份或替代使用本地Docker重启策略和/或SystemD服务单元来控制系统启动时容器的启动。

我觉得我提到这个答案的唯一原因是一种非理性的情绪反应,因为为了使SystemD服务单元方法正常工作,您必须正确处理过于复杂和大量的事情,因为这样一个简单的任务在任何Linux机器上都应该是简单的。

我想在Windows上实现启动容器启动。

因此,我只是创建了一个在系统引导时启动的计划任务。该任务只是启动“Docker for Windows.exe”(或任何Docker可执行文件的名称)。

然后,所有重新启动策略为“always”的容器将启动。

缺省情况下,重启策略为no。

对于已创建的容器,使用docker update更新重启策略。

docker update --restart=always 0576df221c0b

0576df221c0b是容器id。