Linux

Systemd 单元管理、Drop-in 覆盖与日志排障

直接修改 /lib/systemd/system/ 下的包管理单元文件会在系统升级时被覆盖。稳妥的做法是统一在 /etc/systemd/system/<service>.d/ 中写入 drop-in 片段,并用 systemctl cat 验证合并结果。

1. 使用 RuntimeDirectory 持久化运行时目录

Linux 的 /run 挂载在 tmpfs 内存中,重启后手动创建的子目录会消失。需要在重启后自动重建套接字目录时,直接交给 systemd 管理即可:

[Service]
RuntimeDirectory=app-ipc
RuntimeDirectoryMode=0755
LimitNOFILE=65535

2. 变更单元后的标准验证顺序

# 重新载入单元定义并核对合并后的有效配置
sudo systemctl daemon-reload
sudo systemctl cat nginx.service

# 检查是否存在失败单元
systemctl --failed --no-pager

# 按时间范围与优先级排查服务日志
sudo journalctl -u nginx.service --since "2 hours ago" -p warning..err --no-pager
经验提示: 排查定时任务时,同时查看 systemctl list-timers --all 与对应 .service 的 Result 属性,避免只看到 timer 处于 waiting 就误判上次任务成功。

3. 常用状态核对表

排查目标推荐命令
查看生效参数(不含注释)systemctl show -p ExecStart,User,LimitNOFILE foo.service
验证单元语法是否有误systemd-analyze verify /etc/systemd/system/foo.service
查看系统启动耗时瓶颈systemd-analyze blame | head -n 15