用了这么久 Linux 还是会偶尔忘 systemd 的命令,干脆整理一份留着查。

服务管理

# 启动 / 停止 / 重启服务
systemctl start nginx
systemctl stop nginx
systemctl restart nginx

# 重新加载配置(不中断服务)
systemctl reload nginx

# 查看服务状态
systemctl status nginx

# 开机自启 / 禁用自启
systemctl enable nginx
systemctl disable nginx

# 同时启动并设置开机自启
systemctl enable --now nginx

查看日志

systemd 用 journald 统一管理日志,告别满地散落的 log 文件:

# 查看某个服务的日志
journalctl -u nginx

# 实时跟踪日志(相当于 tail -f)
journalctl -u nginx -f

# 查看最近 100 行
journalctl -u nginx -n 100

# 查看某个时间段的日志
journalctl -u nginx --since "2025-10-01" --until "2025-10-18"

# 查看本次启动以来的日志
journalctl -u nginx -b

# 查看内核日志
journalctl -k

系统状态

# 查看所有运行中的服务
systemctl list-units --type=service --state=running

# 查看启动失败的服务
systemctl --failed

# 查看系统资源占用(类似 top,但按 cgroup 分组)
systemd-cgtop

定时任务

systemd timer 可以替代 cron,优点是能用 journalctl 查日志。

创建一个简单的定时任务需要两个文件:

服务文件 /etc/systemd/system/backup.service

[Unit]
Description=Backup Script

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh

定时器文件 /etc/systemd/system/backup.timer

[Unit]
Description=Run backup daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

启用定时器:

systemctl enable --now backup.timer

# 查看所有定时器
systemctl list-timers

分析启动速度

# 查看启动总耗时
systemd-analyze

# 查看各服务启动耗时,从慢到快排列
systemd-analyze blame

# 生成启动瀑布图(SVG 格式)
systemd-analyze plot > boot.svg

基本够日常用了,有新的再补充。