linux Cheatsheet

systemd 服务管理速查表

systemd 服务管理一页速查:systemctl start/stop/reload/enable 启停自启、status/is-active/list-units 状态查看、journalctl -u/-f/-p err/--since 日志过滤,以及 timer 定时任务替代 crontab 的用法。

把 systemd 服务管理、状态查看、日志排查和 timer 定时任务按组整理成一页,服务起停和查日志时直接对照。

systemdsystemctljournalctl服务

服务管理

  • systemctl start nginx
    启动服务
  • systemctl stop nginx
    停止服务
  • systemctl restart nginx
    重启服务,会断连接
  • systemctl reload nginx
    平滑重载配置,不断连接,不是所有服务都支持
  • systemctl enable nginx
    设置开机自启,加 --now 同时启动
  • systemctl disable nginx
    取消开机自启

状态查看

  • systemctl status nginx
    查看服务状态和最近日志,最常用
  • systemctl is-enabled nginx
    查看是否开机自启
  • systemctl is-active nginx
    查看当前是否运行
  • systemctl list-units --type=service
    列出所有已加载的服务单元
  • systemctl list-units --failed
    列出失败的服务,排查启动异常

日志排查

  • journalctl -u nginx
    查看指定服务日志
  • journalctl -u nginx -f
    实时跟踪服务日志
  • journalctl --since "10 min ago" -u nginx
    查看最近 10 分钟日志
  • journalctl -p err -b
    查看本次启动以来的 error 及以上级别日志
  • journalctl --disk-usage
    查看 journal 日志占用磁盘大小

timer 定时任务

  • systemctl list-timers
    列出所有定时任务,替代 crontab -l
  • systemctl status <timer>
    查看指定 timer 状态和下次执行时间
  • systemctl start <timer> && systemctl enable <timer>
    启用并设置开机自启 timer
  • journalctl -u <timer>
    查看 timer 触发的服务日志
  • systemd-analyze time
    查看本次启动耗时

容易踩的坑

  • reload 是平滑重载配置不会断连接,restart 会重启进程;不是所有服务都支持 reload,nginx 支持。
  • journalctl 日志默认会轮转,--disk-usage 太大时用 journalctl --vacuum-size=100M 清理。
  • timer 比 crontab 更可控,能在 journalctl 里看执行日志,且支持依赖关系。