systemctl 是 systemd 的主管理工具,统一控制服务生命周期、开机行为和系统状态,替代 service 和 chkconfig,操作更一致、依赖更清晰、反馈更详细。

systemctl 是 systemd 系统的主管理工具,用来统一控制服务生命周期、开机行为和系统状态。它替代了旧版 Linux 中零散的 service 和 chkconfig 命令,操作更一致、依赖更清晰、反馈更详细。
查看服务当前状态
用 status 查看服务是否运行、最近日志、启动时间、PID 等关键信息:
systemctl status nginx
输出中会显示:
-
Active:后面是active (running)或inactive (dead),表示运行状态 -
Loaded:显示服务单元文件路径及是否启用自启 -
Main PID:当前进程 ID - 最后几行是最近的日志(含错误提示,排查问题时重点看)
想快速判断服务是否在跑,可用:
systemctl is-active nginx # 返回 active 或 inactive systemctl is-enabled nginx # 返回 enabled 或 disabled
启动、停止与重启服务
这些命令只影响当前会话,重启后不保留:
sudo systemctl start nginx # 启动服务(不设开机自启) sudo systemctl stop nginx # 停止服务 sudo systemctl restart nginx # 先停再启,有短暂中断 sudo systemctl reload nginx # 仅重载配置(如 nginx -s reload),服务不断连(需服务本身支持) sudo systemctl reload-or-restart nginx # 能 reload 就 reload,否则 fallback 到 restart
⚠️ 注意:多数操作需要 sudo 权限;reload 并非所有服务都支持(比如 sshd 支持,redis 默认不支持)。
设置开机自启或禁用自启
这类操作修改的是“系统启动时的行为”,不影响当前运行状态:
sudo systemctl enable nginx # 创建软链接,使服务随 multi-user.target 启动 sudo systemctl disable nginx # 移除软链接,取消自启 sudo systemctl enable --now nginx # 启用自启 + 立即启动(一步到位) sudo systemctl disable --now nginx # 禁用自启 + 立即停止
启用后,可验证:
systemctl is-enabled nginx # 应返回 enabled ls /etc/systemd/system/multi-user.target.wants/ | grep nginx
彻底禁止服务启动(含依赖触发)
mask 比 disable 更严格:它把服务链接到 /dev/null,连其他服务依赖它时也无法间接拉起:
sudo systemctl mask nginx # 彻底屏蔽,任何方式都无法启动 sudo systemctl unmask nginx # 解除屏蔽,恢复正常使用
适用场景:临时禁用关键服务(如 NetworkManager)避免干扰调试,或防止被其他单元意外激活。
批量与辅助操作
-
查看所有正在运行的服务:
systemctl list-units --type=service --state=running
-
查看所有已安装但未启用的服务:
systemctl list-unit-files --type=service --state=disabled
-
查看某个服务的依赖关系(谁依赖它?它依赖谁?):
systemctl list-dependencies nginx systemctl list-dependencies --reverse nginx # 反向查谁依赖它
-
查看服务日志(比
status更全):journalctl -u nginx -n 50 --no-pager # 查最后 50 行 journalctl -u nginx -f # 实时跟踪日志(类似 tail -f)
不复杂但容易忽略。











