服务起不来时,很多人第一反应是翻应用日志。其实 systemd 已经把标准输出、错误输出和启动过程都收进了 journal,先看 systemd 的信息往往更快定位。本文整理一套排查套路和几个真实案例。
一、三板斧:先看状态、再看日志
systemctl status nginx -l # -l 不截断输出
systemctl is-active nginx
systemctl is-failed nginx
journalctl -u nginx -n 100 --no-pager
journalctl -u nginx -f # 实时跟踪
status 里重点看三处:
- Active:
active (running)/failed/activating (auto-restart); - Loaded:单元文件是否 found / masked / not-found;
- Main PID 和随后的
status=xxx错误码。
二、journalctl 常用参数
| 参数 | 作用 | 示例 |
|---|---|---|
-u | 按 unit 过滤 | journalctl -u mysqld |
-f | 实时跟踪 | journalctl -u nginx -f |
--since / --until | 按时间过滤 | journalctl --since "2026-11-20 09:00" |
-n | 显示末尾 N 行 | journalctl -n 200 |
-p err | 只看错误级别以上 | journalctl -p err -b |
-b | 本次启动以来的日志 | journalctl -b -1 查看上次启动 |
-o short-precise | 显示精确时间 | 排查重启时序问题 |
--no-pager | 不用分页器 | 脚本里抓取时用 |
三、典型故障案例
案例 1:status=203/EXEC
现象:Failed to start xxx: No such file or directory,status=203/EXEC。
原因:ExecStart 里的路径不存在、脚本没有执行权限,或者脚本第一行 shebang 指向了解释器的错误路径。
排查:
systemctl cat xxx | grep ExecStart # 看实际执行的命令
ls -l /path/to/script.sh # 权限与 shebang
head -1 /path/to/script.sh # 必须是 #!/bin/bash 等
cat -A script.sh | head -1 # Windows 传来的 CRLF 会显示 ^M
CRLF 是常见坑:Windows 编辑后上传到 Linux,#!/bin/bash\r 找不到解释器。用 dos2unix 或 sed -i 's/\r$//' 修掉。
广告
案例 2:status=1/FAILURE,应用自己退出
现象:status=1/FAILURE,journal 里有应用打印的异常栈。这时 systemd 的配置没问题,是应用本身起不来。
排查:先看 journal 里的异常,再看应用自己的日志文件:
journalctl -u myapp -n 200 --no-pager | tail -50
# 常见原因:端口被占用、配置文件路径错、数据库连不上
ss -lntp | grep 8080
案例 3:status=217/USER
现象:用户不存在。ExecStart 前用 User=xxx 指定了用户,但该用户被删了或写错。
id xxx
systemctl cat xxx | grep -E 'User|Group'
案例 4:依赖服务没起来
现象:应用启动时报连不上数据库/缓存,但单独启动数据库后服务正常。
解决:在 unit 里声明依赖与顺序:
[Unit]
After=network-online.target mysqld.service
Wants=network-online.target
Requires=mysqld.service
注意 After 只管顺序不管成败,要强制依赖用 Requires / BindsTo。
案例 5:改了 unit 文件没生效
现象:改完 /etc/systemd/system/xxx.service,systemctl restart 后行为没变。
解决:必须重载:
systemctl daemon-reload
systemctl restart xxx
四、常见 status 码速查
| status 码 | 含义 |
|---|---|
| 203/EXEC | 可执行文件找不到 / 无权限 / shebang 错误 |
| 217/USER | 指定的用户不存在 |
| 1/FAILURE | 进程退出码 1,多为应用自身错误 |
| 2/FAILURE | 进程退出码 2 |
| 137/KILL | 被 SIGKILL,多半是 OOM |
| 143/TERM | 被 SIGTERM 正常终止 |
| 7 | 程序未正确执行 |
五、单元文件语法自检
systemd-analyze verify /etc/systemd/system/xxx.service
systemd-analyze blame # 开机耗时排序,排查启动慢
六、排查顺序总结
status 看错误码 → journalctl -u 看详细日志 → 对号入座处理 → daemon-reload + restart 验证。按这个顺序,90% 的 systemd 启动问题都能快速定位。