命令速查

systemd

2026-08-25

systemd 相关命令面试/日常运维主要记 systemctljournalctl,再补充几个常用的 systemd 工具即可。

1. systemctl:管理服务

# 查看服务状态
systemctl status nginx

# 启动
systemctl start nginx

# 停止
systemctl stop nginx

# 重启
systemctl restart nginx

# 重载配置,不重启进程
systemctl reload nginx

# 重启失败时常用
systemctl daemon-reload

daemon-reload 特别容易和 reload 混淆:

systemctl reload nginx
# 让 nginx 重新读取自己的配置

systemctl daemon-reload
# 让 systemd 重新读取 .service 文件

如果修改 /etc/systemd/system/myapp.service

sudo systemctl daemon-reload
sudo systemctl restart myapp

2. 开机自启动

# 设置开机启动
systemctl enable nginx

# 取消开机启动
systemctl disable nginx

# 立即启动 + 设置开机启动
systemctl enable --now nginx

# 取消开机启动 + 立即停止
systemctl disable --now nginx

# 查看是否设置开机启动
systemctl is-enabled nginx

3. 查看服务

# 查看服务状态
systemctl status nginx

# 查看所有正在运行的 service
systemctl list-units --type=service

# 查看所有 service,包括未运行的
systemctl list-units --type=service --all

# 查看所有已安装的 service 文件
systemctl list-unit-files --type=service

# 查看某个服务是否运行
systemctl is-active nginx

# 查看某个服务是否设置开机启动
systemctl is-enabled nginx

4. journalctl:查看日志

这是 systemd 日志排查最重要的命令。

# 查看全部日志
journalctl

# 查看指定服务日志
journalctl -u nginx

# 查看指定服务最近日志
journalctl -u nginx -n 100

# 实时查看日志
journalctl -u nginx -f

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

# 查看上一次启动的日志
journalctl -b -1

# 查看最近一小时
journalctl --since "1 hour ago"

# 查看指定时间
journalctl --since "2026-08-25 10:00:00"

# 查看错误级别日志
journalctl -p err

# 查看指定服务的错误日志
journalctl -u nginx -p err

实际排查服务启动失败时,通常:

systemctl status myapp
journalctl -u myapp -n 100

如果需要实时观察:

journalctl -u myapp -f

5. 查看 service 配置

# 查看 systemd 最终加载的配置
systemctl cat nginx

# 查看 service 的详细属性
systemctl show nginx

# 查看 service 文件位置
systemctl show nginx -p FragmentPath

例如:

systemctl cat nginx

可以直接看到类似:

[Unit]
Description=The nginx HTTP Server
After=network.target

[Service]
ExecStart=/usr/sbin/nginx
Restart=on-failure

[Install]
WantedBy=multi-user.target

6. systemd 常见目录

/etc/systemd/system/
# 管理员自己写的 service,优先级高

/usr/lib/systemd/system/
# 软件包安装的 service

/run/systemd/system/
# 运行时生成的 unit

部署 Go / Python / Java 后端时,创建

/etc/systemd/system/myapp.service

然后

sudo systemctl daemon-reload
sudo systemctl enable --now myapp

7. 常见 systemd 工具

systemd-analyze

查看 systemd 总体启动情况。

systemd-analyze blame

查看哪些服务启动最慢。

systemd-analyze critical-chain

查看启动依赖链。

hostnamectl

查看/修改主机名。

timedatectl

查看/设置系统时间、时区和 NTP。

loginctl

管理用户登录会话。