自动启动容器
Docker 提供了 重启策略 来控制您的容器在退出时或 Docker 重启时是否自动启动。重启策略会以正确的顺序启动链接的容器。 Docker 建议您使用重启策略,并避免使用进程管理器来启动容器。
重启策略与dockerd命令的--live-restore标志不同。使用--live-restore可以让您在Docker升级期间保持容器运行,尽管网络和用户输入会被中断。
使用重启策略
要配置容器的重启策略,请在使用docker run命令时使用--restart标志。--restart标志的值可以是以下任意一种:
| Flag | Description |
|---|---|
no | Don't automatically restart the container. (Default) |
on-failure[:max-retries] | Restart the container if it exits due to an error, which manifests as a non-zero exit code. Optionally, limit the number of times the Docker daemon attempts to restart the container using the :max-retries option. The on-failure policy only prompts a restart if the container exits with a failure. It doesn't restart the container if the daemon restarts. |
always | Always restart the container if it stops. If it's manually stopped, it's restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in 重启策略详情) |
unless-stopped | Similar to always, except that when the container is stopped (manually or otherwise), it isn't restarted even after Docker daemon restarts. |
以下命令启动一个Redis容器,并配置它始终重启,除非容器被显式停止,或者守护进程重启。
$ docker run -d --restart unless-stopped redis
以下命令更改了名为 redis 的正在运行的容器的重启策略。
$ docker update --restart unless-stopped redis
以下命令确保所有正在运行的容器重新启动。
$ docker update --restart unless-stopped $(docker ps -q)
重启策略详情
使用重启策略时请记住以下几点:
重启策略仅在容器成功启动后生效。在这种情况下,成功启动意味着容器至少运行了10秒,并且Docker已经开始监控它。这可以防止根本无法启动的容器进入重启循环。
如果您手动停止一个容器,重启策略将被忽略,直到Docker守护进程重启或容器被手动重启。这可以防止重启循环。
重启策略仅适用于容器。要为Swarm服务配置重启策略,请参阅 与服务重启相关的标志。
重启前台容器
当你在前台运行一个容器时,停止容器会导致附加的 CLI 也退出,无论容器的重启策略如何。以下示例展示了这种行为。
创建一个Dockerfile,打印数字1到5然后退出。
FROM busybox:latest COPY --chmod=755 <<"EOF" /start.sh echo "Starting..." for i in $(seq 1 5); do echo "$i" sleep 1 done echo "Exiting..." exit 1 EOF ENTRYPOINT /start.sh从Dockerfile构建镜像。
$ docker build -t startstop .从镜像运行一个容器,指定其重启策略为
always。容器将数字1..5打印到标准输出,然后退出。这也会导致附加的CLI退出。
$ docker run --restart always startstop Starting... 1 2 3 4 5 Exiting... $运行
docker ps显示由于重启策略,容器仍在运行或重启中。然而,CLI会话已经退出。它不会在容器初次退出后继续存在。$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 081991b35afe startstop "/bin/sh -c /start.sh" 9 seconds ago Up 4 seconds gallant_easley你可以在重启之间使用
docker container attach命令重新将终端附加到容器。下次容器退出时,它会再次分离。$ docker container attach 081991b35afe 4 5 Exiting... $
使用进程管理器
如果重启策略不适合您的需求,例如当Docker外部的进程依赖于Docker容器时,您可以使用进程管理器,如systemd或supervisor来代替。
警告
不要将Docker重启策略与主机级别的进程管理器结合使用,因为这会产生冲突。
要使用进程管理器,请配置它以使用您通常用于手动启动容器的相同docker start或docker service命令来启动您的容器或服务。有关更多详细信息,请查阅特定进程管理器的文档。
在容器内使用进程管理器
进程管理器也可以在容器内运行,以检查进程是否正在运行,如果没有运行则启动/重新启动它。
警告
这些不是Docker感知的,仅监控容器内的操作系统进程。Docker不推荐这种方法,因为它是平台依赖的,并且可能在给定Linux发行版的不同版本之间有所不同。