systemd 服务编写入门:一个可靠守护进程的正确姿势

很多人部署服务时习惯用 nohup xxx &,甚至 screen。这在测试环境没问题,但到了生产环境,进程挂了不会自动拉起,重启机器后也不会自启。systemd 才是正解。

一个最基本的 unit 文件

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

[Service]
Type=simple
ExecStart=/usr/local/bin/myapp
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

放到 /etc/systemd/system/myapp.service,然后 systemctl daemon-reload && systemctl enable --now myapp 即可。

Type 的选择

选错 Type 会导致 systemd 误判服务状态。

环境变量与资源限制

[Service]
EnvironmentFile=/etc/myapp/env
Environment=NODE_ENV=production
LimitNOFILE=65535
Restart=on-failure

Restart=on-failurealways 更推荐——只有异常退出才重启,避免服务因正常退出(如收到 SIGTERM)而不停被拉起造成死循环。

日志

服务输出会被 systemd 捕获,用 journalctl -u myapp -f 即可实时查看。别忘了在应用里把日志写到 stdout,而不是自己写文件。

小结

一个可靠的守护进程,本质是「异常能自愈、开机能自启、日志能追溯」。systemd 这三件事都替你做好了,值得花半小时真正掌握。