Press "Enter" to skip to content

让systemd崩溃的服务能够自动恢复

Systemd允许您配置服务,以使其在崩溃时自动重新启动。

弄一个看起来像这样的典型配置文件。

$ cat /etc/systemd/system/yourdaemon.service
[Unit]
Description=Your Daemon
After=network-online.target
Wants=network-online.target systemd-networkd-wait-online.service

[Service]
ExecStart=/path/to/daemon

[Install]
WantedBy=multi-user.target

大多数的配置文件都要比这个长,这里只是展示了一些关键的配置信息。 在上面的示例中,如果您的守护程序崩溃或被杀死,systemd将不理会它。

但是,您可以让systemd自动重新启动它,以防它失败或被意外杀死。 为此,您可以在[Service]节中添加Restart选项。

$ cat /etc/systemd/system/yourdaemon.service
[Unit]
Description=Your Daemon
After=network-online.target
Wants=network-online.target systemd-networkd-wait-online.service

StartLimitIntervalSec=500
StartLimitBurst=5

[Service]
Restart=on-failure
RestartSec=5s

ExecStart=/path/to/daemon

[Install]
WantedBy=multi-user.target

上面的内容将对停止您的守护程序的任何内容作出反应:代码异常,确实杀死了-9 ,…一旦守护程序停止,systemd将在5秒钟内重新启动它。

在此示例中,[Unit]部分中也有StartLimitIntervalSec和StartLimitBurst伪指令。 这样可以防止失败的服务每5秒重新启动一次,一直循环下去。 这将给它5次尝试,如果仍然失败,则systemd将停止尝试启动该服务。

(注意:如果更改了systemd单位文件,请确保运行systemctl daemon-reload以重新加载更改。)

如果您在杀死守护程序后询问其状态,systemd将显示正在激活(自动重启)。

$ systemctl status yourdaemon
● yourdaemon.service - Your Daemon
   Loaded: loaded (/etc/systemd/system/yourdaemon.service; enabled; vendor preset: enabled)
   Active: activating (auto-restart) (Result: signal) since Mon 2020-01-13 09:07:41 UTC; 4s ago
  Process: 27165 ExecStart=/path/to/daemon (code=killed)
  Main PID: 27165 (code=killed, signal=KILL)

稍等片刻,您将看到守护进程已由systemd自动重启。

$ systemctl status yourdaemon
● yourdaemon.service - Your Daemon
   Loaded: loaded (/etc/systemd/system/yourdaemon.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2020-01-13 09:07:46 UTC; 6min ago

Pretty useful if you have a buggy service that’s safe to just restart on failure!

引自:https://ma.ttias.be/auto-restart-crashed-service-systemd/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注