为什么用 systemd

nohup & 挂了就没了,重启服务器也不会自动起。systemd 能做到:崩溃自动重启、日志自动收集、开机自启、资源限制。

一个完整的 service 文件

[Unit]
Description=My Data Collector
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/collector
ExecStart=/opt/collector/bin/collector --config /etc/collector.yaml
Restart=always
RestartSec=5
StandardOutput=journal+console
StandardError=journal+console

[Install]
WantedBy=multi-user.target

常用命令

# 放到 /etc/systemd/system/collector.service
systemctl daemon-reload          # 改了文件要重载
systemctl enable collector       # 开机自启
systemctl start collector        # 启动
systemctl status collector       # 看状态
journalctl -u collector -f      # 实时看日志
journalctl -u collector --since "1 hour ago"  # 看最近1小时

Restart 策略