Docker原生支持Restart策略,是最简单、最直接的自动重启方式,适用于大多数场景。策略类型包括:
no(默认):容器退出后不自动重启;on-failure:容器以非0状态码退出时自动重启(可指定最大重启次数,如on-failure:5表示最多重启5次);always:无论退出状态码如何,容器退出后总是自动重启;unless-stopped:容器总是自动重启,除非被手动停止。使用docker run命令时,通过--restart参数指定策略,例如:
docker run -d --restart always --name my_container my_image
上述命令会启动一个名为my_container的容器,即使容器因故障退出,也会自动重启。
若容器已在运行,可使用docker update命令动态调整重启策略,例如:
docker update --restart always my_container
此命令会将my_container的策略改为“总是自动重启”。
使用docker inspect命令查看容器的当前重启策略,例如:
docker inspect --format='{{.HostConfig.RestartPolicy}}' my_container
输出结果会显示容器的RestartPolicy类型(如always)。
若使用Docker Compose管理容器,可在docker-compose.yml文件中为服务指定重启策略,例如:
version: '3'
services:
my_service:
image: my_image
restart: always # 或 on-failure、unless-stopped
保存文件后,运行docker-compose up -d启动服务,容器会根据策略自动重启。
若需更复杂的自动重启逻辑(如定时检查),可创建自定义脚本并通过systemd设置为系统服务:
/path/to/restart.sh),内容为重启容器的命令:#!/bin/bash
docker restart my_container
赋予脚本执行权限:chmod +x /path/to/restart.sh。/path/to/daemon.sh),定时调用重启脚本:#!/bin/bash
while true; do
/path/to/restart.sh
sleep 3600 # 每隔1小时执行一次
done
systemd服务文件(如/etc/systemd/system/docker-autorestart.service),内容如下:[Unit]
Description=Docker Auto Restart Service
[Service]
ExecStart=/path/to/daemon.sh
[Install]
WantedBy=default.target
sudo mv docker-autorestart.service /etc/systemd/system/
sudo systemctl enable docker-autorestart.service
sudo systemctl start docker-autorestart.service
此方案适用于需要额外控制(如日志记录、条件判断)的场景,但配置复杂度较高。systemd服务正常运行,避免守护进程崩溃导致自动重启失效;sudo systemctl enable docker设置,确保主机重启后Docker服务自动启动。