Skip to content

systemd 服务管理

日常命令

bash
systemctl status nginx          # 状态 + 最近几行日志
systemctl start|stop|restart nginx
systemctl reload nginx          # 重读配置,不断连接(服务得支持)
systemctl enable --now nginx    # 开机自启并立刻启动
systemctl disable --now nginx   # 反过来

enablestart 是两回事。只 start 重启就没了,只 enable 得等下次开机。--now 一步到位。

看日志

bash
journalctl -u nginx                 # 全部
journalctl -u nginx -f              # 跟着看
journalctl -u nginx --since "1 hour ago"
journalctl -u nginx -n 100 --no-pager
journalctl -p err -b                # 本次启动以来所有 error 级别

日志占太多磁盘:

bash
journalctl --disk-usage
journalctl --vacuum-size=200M

永久限制在 /etc/systemd/journald.conf 里设 SystemMaxUse=200M

改 unit 文件不要直接改

/usr/lib/systemd/system/ 下的文件包升级会覆盖。要改用 override:

bash
systemctl edit nginx

会在 /etc/systemd/system/nginx.service.d/override.conf 生成片段,只写要改的项:

ini
[Service]
Restart=always
RestartSec=3

改完 systemctl daemon-reload 再 restart。

Restart= 的几个值

  • on-failure:非零退出、被信号杀死、超时才重启。多数服务用这个够了
  • always:不管怎么退出都重启,包括正常 stop 后自己退出的情况
  • no:默认,不重启

有些服务进程活着但功能已经卡死,systemd 看不出来,这种得自己写健康检查配 cron。

查哪个 unit 拖慢了开机

bash
systemd-analyze blame | head
systemd-analyze critical-chain

顺手关掉不用的

新装的 RHEL 系机器登录提示里如果有 Web console: https://xxx:9090,是 Cockpit 在跑。不用就关:

bash
systemctl disable --now cockpit.socket

个人笔记,写给未来忘事的自己。