073 systemctl命令

命令说明

systemctl 是 systemd 的统一管理入口,负责服务的启动/停止/重启/状态、开机自启、单元与日志关联管理,是现代 Linux(RHEL7+/Ubuntu16+)运维的必修命令。

语法

systemctl [选项]... 命令 [单元]

常用参数

参数说明
start / stop / restart启动 / 停止 / 重启服务,如 systemctl start nginx
reload重载配置不重启(服务需支持 SIGHUP)
status 单元查看运行状态、主 PID、最近日志
enable / disable设置 / 取消开机自启
is-enabled / is-active脚本判断:是否自启 / 是否运行中
daemon-reload修改 unit 文件后重新加载 systemd 配置
list-units --type=service列出全部服务单元及状态
failed列出所有启动失败的服务(排障入口)
mask / unmask彻底屏蔽单元(连手动启动都不行)/ 解除
edit 单元创建/编辑 override 片段定制服务配置
show 单元查看单元全部属性(ExecStart、依赖等)

使用示例

$ systemctl status firewalld

查看防火墙服务状态与日志摘要

$ systemctl enable --now nginx

设置自启并立即启动(一步到位)

$ systemctl restart sshd

重启 SSH 服务(改配置后)

$ systemctl daemon-reload

改完 /etc/systemd/system/*.service 后必须先执行

$ systemctl list-units --type=service --state=running

列出运行中的服务

$ systemctl list-unit-files | grep enabled

查看哪些单元开了自启

$ systemctl cat nginx

查看 unit 文件内容(含 override)

$ systemctl edit docker

追加 override 配置(如加环境变量)

$ systemctl disable --now apache2

停服务并取消自启

$ journalctl -u nginx -f

跟踪查看该服务日志(配套命令)

实用技巧

  • 改 unit 文件后必须 systemctl daemon-reload 再 restart,否则改动不生效——这是 systemctl 第一大坑。
  • 服务起不来标准排障链:systemctl status 看退出码 → journalctl -u 服务 看详细报错 → systemctl cat 看配置 → 手动跑 ExecStart 复现。
  • reload 与 restart 区别:reload 发 SIGHUP 让进程平滑重载配置不断连接(nginx);不支持 reload 的服务会报错,此时只能 restart。
  • enable 只管开机自启不影响当前运行,start 只管当前不管自启;--now 组合两者。mask 比 disable 更狠,用于彻底封禁某服务(如屏蔽 clamav 与 docker 冲突)。
  • 与老命令对应:service x start → systemctl start x;chkconfig x on → systemctl enable x;systemctl 是 RHEL7+ 统一标准,Debian 系同样适用。
  • 退出码含义:status 里 Active: failed (Result: exit-code) 配合 Main PID 与 Exit Code 定位;ExecStart 路径错误是最常见原因。