Linux 中管理服务的命令主要分为 传统 service 命令 和 主流 systemctl 命令 两类,其中 systemctl 是 Systemd 系统的标准工具,目前绝大多数 Linux 发行版(如 CentOS 7+、Ubuntu 16.04+)都已采用,功能更全面。
一、 主流工具:systemctl(Systemd 系统)
systemctl 可以实现服务的启动、停止、重启、开机自启、状态查询等全生命周期管理,基本语法:
systemctl [操作] [服务名].service
注:
.service后缀可省略。
| 操作命令 | 作用 | 测试场景示例 |
|---|---|---|
systemctl start 服务名 |
启动指定服务 | systemctl start nginx(启动 Nginx 服务,用于 Web 测试环境) |
systemctl stop 服务名 |
停止指定服务 | systemctl stop mysql(停止 MySQL 数据库,用于测试环境维护) |
systemctl restart 服务名 |
重启指定服务 | systemctl restart tomcat(重启 Tomcat 服务,测试配置文件修改是否生效) |
systemctl reload 服务名 |
重载服务配置(不中断服务) | systemctl reload nginx(重载 Nginx 配置,无需重启服务) |
systemctl status 服务名 |
查看服务运行状态 | systemctl status redis(检查 Redis 是否正常运行,判断缓存服务可用性) |
systemctl enable 服务名 |
设置服务开机自启 | systemctl enable docker(确保 Docker 服务随系统启动,测试容器化环境) |
systemctl disable 服务名 |
关闭服务开机自启 | systemctl disable httpd(禁止 Apache 开机自启,避免占用测试端口) |
systemctl is-active 服务名 |
检查服务是否正在运行 | systemctl is-active jenkins(快速判断 Jenkins 测试任务调度服务状态) |
systemctl is-enabled 服务名 |
检查服务是否开机自启 | systemctl is-enabled mysql(确认数据库是否配置为开机自启) |
补充常用命令
-
查看所有已启动的服务: bash
运行
systemctl list-units --type=service --state=running -
查看所有服务(包括未启动的): bash
运行
systemctl list-unit-files --type=service -
禁止服务被手动或自动启动(冻结服务): bash
运行
systemctl mask 服务名 -
解除服务冻结: bash
运行
systemctl unmask 服务名
二、 传统工具:service 命令(SysVinit 系统)
适用于老旧 Linux 发行版(如 CentOS 6、Ubuntu 14.04),通过 /etc/init.d/ 目录下的服务脚本管理,功能较简单。基本语法:
bash
运行
service [服务名] [操作]
| 操作命令 | 作用 | 示例 |
|---|---|---|
service 服务名 start |
启动服务 | service nginx start |
service 服务名 stop |
停止服务 | service mysql stop |
service 服务名 restart |
重启服务 | service tomcat restart |
service 服务名 status |
查看服务状态 | service redis status |
补充
查看系统中所有可用的 service 服务:
bash
运行
service --status-all
三、 两类命令的区别与适用场景
| 特性 | systemctl |
service |
|---|---|---|
| 适用系统 | Systemd(主流新系统) | SysVinit(老旧系统) |
| 功能 | 支持开机自启、依赖管理、日志关联 | 仅支持基础启停、状态查询 |
| 日志集成 | 可通过 journalctl -u 服务名 查看服务日志 |
需单独查看日志文件(如 /var/log/) |
四、 测试场景常用技巧
-
查看服务日志(
systemctl配套命令):bash
运行
journalctl -u 服务名 # 查看指定服务的所有日志 journalctl -u nginx -f # 实时跟踪 Nginx 服务日志(类似 tail -f) -
解决服务启动失败:先通过
systemctl status 服务名查看错误提示,再结合日志定位问题。