Linux 与服务器运维 / 系统课时
使用 systemctl 管理服务
使用 systemctl 管理服务
systemctl 是管理 systemd 单元的主要命令。本节以已安装的 nginx.service 为例,完成服务启动、停止、重启、状态查看和开机自启设置,并说明几组容易混淆的操作。
学习目标
- 使用
systemctl启动、停止和重启服务 - 查看服务当前运行状态并判断是否启动成功
- 设置服务开机自启,并区分“正在运行”和“已启用”
启动、停止和重启服务
系统级服务通常需要管理员权限。以下示例假设机器已经安装 nginx.service;如果你的服务名称不同,应替换成实际 unit 名称。
先启动服务,再用 is-active 做最小化验证:
sudo systemctl start nginx.service
systemctl is-active nginx.service预期输出:
activestart 成功时通常不会额外打印内容,is-active 返回 active 才表示当前服务处于运行状态。
停止服务后再次检查:
sudo systemctl stop nginx.service
systemctl is-active nginx.service预期输出:
inactive此时 is-active 通常还会返回非零退出码,因为服务已经不是 active 状态;这是状态判断结果,不代表 stop 本身失败。
修改配置或需要完整重建进程时,可以重启服务:
sudo systemctl restart nginx.service
systemctl is-active nginx.service预期输出:
active查看服务详细状态
status 会同时显示单元是否加载、当前状态、主进程等信息,适合人工排查。服务处于运行状态时执行:
systemctl status nginx.service --no-pager预期结果会包含类似的关键字段,路径、时间和 PID 以实际机器为准:
Loaded: loaded (<PATH>; <VALUE>)
Active: active (running) since <TIME>
Main PID: <PID>如果只想给脚本读取稳定字段,可以使用 show:
systemctl show nginx.service -p LoadState -p ActiveState -p SubState预期输出:
LoadState=loaded
ActiveState=active
SubState=running设置开机自启
enable 修改的是“开机时是否按依赖关系拉起该单元”,它不等于当前已经运行。下面先启用,再检查启用状态;示例把不同发行版可能出现的软链接提示隐藏,只保留最终验证结果。
sudo systemctl enable nginx.service >/dev/null 2>&1
systemctl is-enabled nginx.service预期输出:
enabled如果希望“现在启动,并且以后开机也自动启动”,可以使用 systemctl enable --now nginx.service。反过来,stop 只影响当前运行状态,disable 只取消开机自启;两者不要混为一谈。
常见失败先看这三类信号
出现 Unit nginx.service not found 时,优先确认服务是否安装以及 unit 名称是否正确。启动后仍不是 active,先查看 systemctl status nginx.service 的错误摘要,再根据其中的提示检查配置、端口占用或依赖失败。
如果服务支持平滑重载,reload 通常比 restart 对连接影响更小;但并非所有服务都实现 reload。实际操作前应确认对应 unit 是否支持该动作,而不是把 reload 当作无条件可用的通用替代。
日常管理可以记住一组最小判断:start/stop/restart 改变当前运行状态,enable/disable 改变开机策略,status/is-active/is-enabled 用来验证结果。