把程序丢进 nohup 是最容易掉的坑——重启机器就没了。正确做法是写一个 unit。

最小可用单元

/etc/systemd/system/demo.service:

[Unit]
Description=Demo Service
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/opt/demo
ExecStart=/opt/demo/demo --config /opt/demo/config.yaml
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

生效

systemctl daemon-reload
systemctl enable --now demo
systemctl status demo
journalctl -u demo -f

几个容易忘的点

  • Type=simple 表示前台运行,别写成 daemon 模式,否则 systemd 会以为进程退出了
  • Restart=on-failure 只对非零退出码生效,想要无条件重启用 always
  • 改完 unit 一定要 daemon-reload,否则改了个寂寞