linux Cheatsheet
systemd 服务管理速查表
systemd 服务管理一页速查:systemctl start/stop/reload/enable 启停自启、status/is-active/list-units 状态查看、journalctl -u/-f/-p err/--since 日志过滤,以及 timer 定时任务替代 crontab 的用法。
把 systemd 服务管理、状态查看、日志排查和 timer 定时任务按组整理成一页,服务起停和查日志时直接对照。
服务管理
- 启动服务
systemctl start nginx - 停止服务
systemctl stop nginx - 重启服务,会断连接
systemctl restart nginx - 平滑重载配置,不断连接,不是所有服务都支持
systemctl reload nginx - 设置开机自启,加 --now 同时启动
systemctl enable nginx - 取消开机自启
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 - 查看最近 10 分钟日志
journalctl --since "10 min ago" -u nginx - 查看本次启动以来的 error 及以上级别日志
journalctl -p err -b - 查看 journal 日志占用磁盘大小
journalctl --disk-usage
timer 定时任务
- 列出所有定时任务,替代 crontab -l
systemctl list-timers - 查看指定 timer 状态和下次执行时间
systemctl status <timer> - 启用并设置开机自启 timer
systemctl start <timer> && systemctl enable <timer> - 查看 timer 触发的服务日志
journalctl -u <timer> - 查看本次启动耗时
systemd-analyze time
容易踩的坑
- reload 是平滑重载配置不会断连接,restart 会重启进程;不是所有服务都支持 reload,nginx 支持。
- journalctl 日志默认会轮转,--disk-usage 太大时用 journalctl --vacuum-size=100M 清理。
- timer 比 crontab 更可控,能在 journalctl 里看执行日志,且支持依赖关系。