linux中配置systemd服务崩溃自动重启,需在.service文件[service]段设置restart=on-failure(推荐)或restart=always,配合restartsec、startlimitintervalsec和startlimitburst防雪崩,并用execstartpost探活、watchdogsec心跳及日志落盘提升可靠性。

Linux 中配置 systemd 服务崩溃自动重启,核心是修改其 .service 文件中的 [Service] 区块,启用并调优原生重启策略——不依赖脚本、不靠轮询,真正由系统级守护进程接管。
确认服务由 systemd 管理
运行以下命令验证:
systemctl status 服务名(例如 systemctl status nginx)
若输出中含 Loaded: loaded (/.../xxx.service; ...),说明已是 systemd 服务;若提示 Unit not found,则需先创建对应 .service 文件,再配置重启逻辑。
设置 Restart 策略与延迟
编辑服务文件(路径通常为 /etc/systemd/system/xxx.service 或 /lib/systemd/system/xxx.service),在 [Service] 段添加:
- Restart=on-failure:推荐默认值。仅在非零退出码、被信号终止(如 SIGSEGV)、启动超时或 OOM kill 时重启,避免误拉起正常退出的服务
- Restart=always:适用于不应“正常退出”的场景(如大模型推理服务),任何退出都重启
- RestartSec=5:重启前等待 5 秒。轻量服务可设 3–5 秒;模型加载类服务建议 10–30 秒,留足初始化时间
加启动频次限制防雪崩
必须配合限流参数,否则持续崩溃会高频拉起进程,拖垮系统:
- StartLimitIntervalSec=60:滚动统计窗口为 60 秒
- StartLimitBurst=3:该窗口内最多允许启动 3 次
- 超出后 systemd 将暂停重启,并标记为
start-limit-hit,此时需人工查日志定位根因,而非等待自动恢复
增强可观测性与真实可用性
systemd 只监控进程是否存活,不感知“假死”或响应卡顿。补充以下手段提升可靠性:
- 用 ExecStartPost 做启动后探活:
ExecStartPost=/bin/sh -c 'sleep 2 && curl -f http://127.0.0.1:8000/health || exit 1'
失败则视为启动失败,触发 Restart 逻辑 - 启用 WatchdogSec=30 并在应用中调用
systemd-notify --watchdog,实现双向心跳 - 添加日志落盘:
StandardOutput=file:/var/log/myapp/out.logStandardError=file:/var/log/myapp/err.log











