Linux systemctl restart=on-failure配置示例

Restart=on-failure 是 systemd 中用于在服务异常退出时自动重启的配置选项,适用于崩溃或非正常终止的情况。它会在服务因非零退出码、信号终止、超时或看门狗触发时重启,但不会在手动停止时启动。示例配置中通过设置 Restart=on-failure 和 RestartSec=5s 实现失败后延时重启,配合 systemctl 命令加载并管理服务,有效提升服务稳定性而不影响手动控制。

linux systemctl restart=on-failure配置示例

当使用 systemd 管理服务时,可以通过配置 Restart=on-failure 实现服务异常退出后自动重启。这种设置适用于大多数守护进程类应用,确保服务在崩溃或意外终止后能自动恢复运行。

什么是 Restart=on-failure

Restart=on-failure 是 systemd 服务单元中的一个选项,表示当服务以非零退出码终止、被信号终止、超时或被看门狗检测为失败时,systemd 会自动重启该服务。它不会在服务被手动停止时触发重启。

配置示例:自定义服务

以下是一个简单的服务配置文件示例,展示如何启用 Restart=on-failure:

[Unit]
Description=My Example Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/myapp
Restart=on-failure
RestartSec=5s
User=myuser
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

关键参数说明:

  • Restart=on-failure:仅在服务失败时重启(退出码非0、被信号杀死等)
  • RestartSec=5s:每次重启前等待5秒,避免频繁重启
  • Type=simple:默认类型,ExecStart 启动主进程

其他 Restart 可选值(简要对比)

虽然当前需求是 on-failure,但了解其他选项有助于准确选择:

万知 万知

万知: 你的个人AI工作站

万知 156 查看详情 万知
  • no:不自动重启(默认行为)
  • always:无论何种方式退出都重启
  • on-abnormal:仅因信号或超时退出时重启,不包括正常退出
  • on-abort:仅因系统中止等严重错误重启
  • on-watchdog:仅当看门狗超时触发时重启

重新加载并启用服务

保存服务文件后(如 /etc/systemd/system/myapp.service),执行以下命令生效:

systemctl daemon-reexec
systemctl daemon-reload
systemctl enable myapp.service
systemctl start myapp.service

可通过以下命令查看服务状态和重启次数:

systemctl status myapp.service

输出中会显示“Active: active (running)”以及最近是否发生过重启。

基本上就这些。合理使用 Restart=on-failure 能显著提升服务的稳定性,又不会过度干扰手动管理操作。

以上就是Linux systemctl restart=on-failure配置示例的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。