Linux systemd 服务管理完全指南——从开机启动到故障排查

systemd 是现代 Linux 的基石。你的 Nginx、MySQL、SSH 都由 systemd 管着。搞懂它,服务挂了才知道从哪看。

服务状态

systemctl status nginx

输出包括:是否在跑、PID、最近日志。是最常用的命令。

启动 / 停止 / 重启

systemctl start nginx    # 启动
systemctl stop nginx     # 停止
systemctl restart nginx  # 重启
systemctl reload nginx   # 重载配置(不中断连接)

开机自启

systemctl enable nginx   # 设为开机自启
systemctl disable nginx  # 取消开机自启
systemctl is-enabled nginx  # 查看是否已启用

查看日志

journalctl -u nginx -f   # 实时看 nginx 日志
journalctl -u nginx --since "10 min ago"  # 最近 10 分钟
journalctl -u nginx -n 50  # 最后 50 行

列出所有服务

systemctl list-units --type=service'
systemctl list-units --type=service --state=failed  # 只看挂掉的

自定义服务文件

把脚本做成 systemd 服务,比 nohup 靠谱一百倍:

# /etc/systemd/system/myapp.service
[Unit]
Description=My App
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/app.js
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

创建后:

systemctl daemon-reload
systemctl enable myapp
systemctl start myapp

常见故障排查

服务启动失败:

journalctl -u nginx -n 50  # 看日志
systemctl status nginx      # 看退出码

改了配置文件没生效:

systemctl daemon-reload  # 重载 unit 文件
systemctl restart nginx

端口被占用:

ss -tlnp | grep 80

总结

五个命令记住就够了:systemctl status start stop enable journalctl -u。服务出问题先看 status 再看 journal,不要一上来就重启。