systemctl 命令详解
更新时间:2026-08-28。本文是「一个命令一个文档」系列,聚焦
systemctl——软件包与服务命令族(见软件包与服务命令族)的核心。现代 Linux 发行版的服务管理几乎全是它。
systemctl 是 systemd(现代 Linux 的初始化系统与服务管理器)的命令行前端。一台服务器上 nginx、mysql、docker 这些"服务"(daemon,后台常驻进程)的启动、停止、开机自启、状态查看,全通过一个 .service 单元文件 + systemctl 来管。
一、启停与自启
systemctl start nginx # 启动
systemctl stop nginx # 停止
systemctl restart nginx # 重启(先停后起)
systemctl reload nginx # 重载配置(不中断服务,如 nginx 改配置后)
systemctl enable nginx # 开机自启
systemctl disable nginx # 取消开机自启
systemctl status nginx # 看状态(最常用)
reload和restart区别很大:reload让进程重读配置、连接不中断(适合 nginx 改了 conf);restart是先杀再起,会有短暂中断。能 reload 就别 restart。enable只是"开机自动起",不会立刻启动——新装服务记得enable+start两步走。
二、看状态:status 是第一反应
systemctl status nginx
# ● nginx.service - A high performance web server
# Loaded: loaded (/lib/systemd/system/nginx.service; enabled; ...)
# Active: active (running) since Thu 08:00:00; 2h ago
# Main PID: 1234 (nginx)
# Tasks: 3
# CGroup: /system.slice/nginx.service
status输出里三处关键:Loaded行看"是否 enabled(开机自启)"和单元文件路径;Active看"running/failed/dead";最底下通常直接附带最近几行日志——服务起不来时,先看Active是不是failed,再顺手从status末尾的日志找原因,省一次 journalctl。
三、单元类型与列出
systemctl list-units --type=service # 列出运行中的服务
systemctl list-unit-files --type=service # 列出所有服务及其开机策略
systemctl is-enabled nginx # 查是否开机自启
systemctl is-active nginx # 查当前是否在跑
systemctl cat nginx # 查看该单元的 service 文件内容systemd 的"单元(unit)"不止 service,还有
socket、timer、mount、target等。list-unit-files看的是"静态配置里的启用策略",list-units看的是"当前加载运行的",两者不同——一个服务enabled但此刻inactive,说明它本应开机起但被人停了。
四、看日志:journalctl
journalctl -u nginx # 某服务的全部日志
journalctl -u nginx -f # 实时跟踪(等同 tail -f)
journalctl -u nginx --since "1 hour ago" # 最近一小时
journalctl -u nginx -p err # 只看 error 级别以上systemd 把日志统一收进 journal(二进制日志),不再散落
/var/log各文件。journalctl -u <服务>是查"这个服务到底报了什么错"的标准入口,配合-f实时跟、--since按时间砍、-p err只看错误,排障效率比翻文本日志高。更多见 日志、时间命令族。
五、mask 与失能:彻底锁死
systemctl mask nginx # 软链到 /dev/null,连手动 start 都禁(最强禁用)
systemctl unmask nginx # 解除 mask
disable只是取消开机自启,你还能手动start;mask更狠——把单元链接到/dev/null,任何方式都起不来,常用于防止某个被依赖冲突的服务意外启动。排查"我明明 start 了却起不来"时,先systemctl is-enabled看看是不是被masked了。
六、实战:服务起不来怎么查
# 1. 看状态,确认 failed 和末尾错误信息
systemctl status myapp -l
# 2. 看完整日志(带时间、级别)
journalctl -u myapp -p err --since "10 min ago"
# 3. 看单元文件有没有写错路径/命令
systemctl cat myapp
# 4. 修正后重载 daemon 再起
systemctl daemon-reload
systemctl restart myapp改了 .service 文件后必须 daemon-reload(通知 systemd 重新读配置),否则改动不生效——这是新手改完服务文件却发现"怎么没变"的头号原因。
相关命令
看服务日志用 journalctl;远程管理用 ssh。
一句话总结
systemctl = systemd 服务管理入口:start/stop/restart/reload 控运行、enable/disable 管开机自启(enable 不立即起,reload 不中断连接)、status 看 Active/Loaded 与末尾日志;日志走 journalctl -u(-f 跟、--since 砍时间、-p err 过滤);改了 service 文件须 daemon-reload;mask 比 disable 更彻底地禁起。服务起不来,先 status 再 journalctl -p err。