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

$ docker run ...

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

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


当前回答

启动容器,并将其设置为在系统重新引导时自动重新启动

docker run -d --restart unless-stopped ecstatic_ritchie

其中,ecstasy atic_ritchie是指定感兴趣的容器的示例名称。使用docker ps -a列出所有容器名称。

使特定的运行容器在系统重新启动时自动启动

docker update --restart unless-stopped ecstatic_ritchie

使所有运行的容器在系统重新启动时自动启动

docker update --restart unless-stopped $(docker ps -q)

详见Docker主页

其他回答

启动容器,并将其设置为在系统重新引导时自动重新启动

docker run -d --restart unless-stopped ecstatic_ritchie

其中,ecstasy atic_ritchie是指定感兴趣的容器的示例名称。使用docker ps -a列出所有容器名称。

使特定的运行容器在系统重新启动时自动启动

docker update --restart unless-stopped ecstatic_ritchie

使所有运行的容器在系统重新启动时自动启动

docker update --restart unless-stopped $(docker ps -q)

详见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.

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

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

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

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

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

这篇博客文章很好地描述了2021年的答案。默认情况下,docker已安装,但未启用。如果你使用的是最新的Ubuntu(例如20),并且你通过apt安装了docker,你所要做的就是sudo systemctl enable—now docker。

这将启用systemd中的docker服务,如果它还没有启动,就立即启动它。docker服务在安装时不会启动,但任何使用docker套接字的docker命令(例如docker ps)都会导致systemd启动该服务。启用该服务将使其每次都在启动时启动。