掌握 systemctl 服务管理需区分“当前运行”和“开机自启”:start/stop/restart 控制即时状态,enable/disable 控制下次启动行为;is-active 检查运行态,is-enabled 检查启用态;status 查状态,journalctl -u -xe 查日志。

掌握 systemctl 启动、停止与重启服务,关键在于分清“当前是否运行”和“开机是否自启”这两个独立状态。命令本身不难,但混淆两者是运维中最常见的失误源头。
服务启停的基本操作
所有基础操作都需 root 权限,建议加 sudo 执行:
- 启动服务:sudo systemctl start nginx(服务名可省略 .service 后缀)
- 停止服务:sudo systemctl stop nginx
- 重启服务:sudo systemctl restart nginx(先 stop 再 start,连接会中断)
- 重载配置:sudo systemctl reload nginx(仅重读配置,进程不重启,适合 Nginx、SSH 等支持 SIGHUP 的服务)
开机自启的设置与验证
enable/disable 控制的是系统下次启动时的行为,和当前服务是否运行无关:
- 设为开机自启:sudo systemctl enable nginx(在 /etc/systemd/system/multi-user.target.wants/ 下创建软链接)
- 取消开机自启:sudo systemctl disable nginx(删除对应软链接)
- 一步到位:用 --now 选项同时完成状态设置与立即执行,例如 sudo systemctl enable --now nginx 相当于先 enable 再 start
- 检查是否启用:systemctl is-enabled nginx(返回 enabled/disabled)
- 检查是否运行:systemctl is-active nginx(返回 active/inactive/failed)
快速诊断服务状态
status 命令输出信息丰富,重点关注三行:
- Loaded:显示单元文件路径及是否启用(enabled),若提示 “disabled” 或 “masked”,说明未正确启用或被屏蔽
- Active:反映当前运行状态,如 “active (running)” 表示正常,“inactive (dead)” 表示已停止,“failed” 表示启动失败
- Main PID:主进程 ID,可用于进一步排查(如 ps -p PID -o pid,comm,args)
- 附加日志:默认只显示最近几行,加 --no-pager -l 可看完整输出,例如 systemctl status nginx --no-pager -l
常见问题与应对方法
服务启停失败时,不要只看 status 输出,要结合日志定位根本原因:
- 服务启动失败:运行 journalctl -u nginx -xe 查看详细错误(-xe 表示显示最新条目并追踪上下文)
- 端口被占用:用 ss -tuln | grep :80 或 lsof -i :80 找出冲突进程
- 依赖服务未就绪:执行 systemctl list-dependencies nginx --reverse 查看哪些服务依赖它,或 --after 查看它依赖谁
- 修改了 .service 文件后必须执行 sudo systemctl daemon-reload,否则新配置不生效











