systemd 托管常驻进程:从 service 文件到日志滚动
用一个 Go 二进制为例,讲透 systemd service 文件的写法:开机自启、崩溃拉起、资源限制、日志查看,以及 nohup 方案为什么该淘汰。
nohup ./app & 跑生产服务属于裸奔:机器一重启就没,崩了没人拉,日志把盘写满。本文用 systemd 一次解决。
1. 最小可用的 service 文件
# /etc/systemd/system/myapp.service
[Unit]
Description=My Go App
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=appuser
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/myapp -config /etc/myapp/config.yaml
Restart=always
RestartSec=3
LimitNOFILE=65535
[Install]
WantedBy=multi-user.target关键项说明:
| 项 | 作用 |
|---|---|
After + Wants network-online | 等网络就绪再起,监听端口的服务必需 |
Restart=always | 退出就拉起,配合 RestartSec 防抖 |
User= | 永远不要用 root 跑业务进程 |
LimitNOFILE | 高并发必加,否则 1024 连接就报错 |
2. 启停与开机自启
systemctl daemon-reload
systemctl enable --now myapp
systemctl status myapp
systemctl restart myapp3. 日志:不要自己写文件
journalctl -u myapp -f # 实时尾随
journalctl -u myapp -S today # 今天的配合滚动上限,日志永远写不满盘:
# /etc/systemd/journald.conf.d/size.conf
[Journal]
SystemMaxUse=100M4. 资源兜底(可选但推荐)
[Service]
MemoryMax=1G
CPUQuota=150%内存泄漏时 systemd 直接 OOM 掉进程再拉起,比整机被拖死强。Go 程序另建议编译时 CGO_ENABLED=0 静态链接,扔到任何发行版都能跑。