Linux命令-service(控制 SysV 风格服务)

📅 2026/7/24 13:42:14 👁️ 阅读次数 📝 编程学习
Linux命令-service(控制 SysV 风格服务)

Linux命令-service(控制 SysV 风格服务)

    • 快速参考
    • 基本语法
    • 安装 service
    • 常用操作
    • service 与 systemctl 对照
    • 现代替代方案:systemctl
    • 从 service 迁移到 systemctl
    • 故障排查
    • 总结

快速参考

service是用于控制 SysV 风格服务的命令行工具。该命令在现代 systemd 系统中已被认为过时,应使用systemctl替代。service仍然广泛用于兼容旧脚本和 SysV init 系统。

现代替代systemctl start/stop/restart/status service_name

基本语法

# 基本语法service服务名{start|stop|restart|reload|force-reload|status}# 启动服务sudoservicesshstart# 停止服务sudoservicesshstop# 重启服务sudoservicesshrestart# 查看服务状态sudoservicesshstatus# 列出所有服务service--status-all

安装 service

# service 是 init-system-helpers 包的一部分(Debian/Ubuntu)sudoaptinstallinit-system-helpers# RHEL/CentOS 通常已预装# 验证安装whichservice

常用操作

# 启动服务sudoservicehttpd start# 停止服务sudoservicehttpd stop# 重启服务sudoservicehttpd restart# 平滑重启(不中断连接)sudoservicehttpd reload# 查看服务状态sudoservicehttpd status# 列出所有服务及其状态sudoservice--status-all# 输出示例:# [ + ] ssh# [ - ] apache2# [ ? ] bluetooth# 说明:# [ + ] :服务正在运行# [ - ] :服务已停止# [ ? ] :无法确定状态

service 与 systemctl 对照

# === 启动服务 ===# 旧方式(service)sudoservicesshstart# 新方式(systemctl)推荐sudosystemctl startssh# === 停止服务 ===sudoservicesshstopsudosystemctl stopssh# === 重启服务 ===sudoservicesshrestartsudosystemctl restartssh# === 查看状态 ===sudoservicesshstatussudosystemctl statusssh# === 启用/禁用开机自启 ===# service 方式(通过 chkconfig 或 update-rc.d)sudochkconfigsshon# RHEL/CentOSsudoupdate-rc.dsshdefaults# Debian/Ubuntu# systemctl 方式(推荐)sudosystemctlenablesshsudosystemctl disablessh

现代替代方案:systemctl

# 查看所有服务状态sudosystemctl list-units--type=service--all# 查看所有已启用的服务sudosystemctl list-unit-files--state=enabled# 启动服务sudosystemctl start service_name# 停止服务sudosystemctl stop service_name# 重启服务sudosystemctl restart service_name# 查看服务状态(详细)sudosystemctl status service_name# 启用服务(开机自启)sudosystemctlenableservice_name# 禁用服务(不开机自启)sudosystemctl disable service_name# 查看服务日志sudojournalctl-uservice_name# 查看服务配置systemctlcatservice_name

从 service 迁移到 systemctl

# 旧方式(service)sudoservicesshstartsudoservicesshstopsudoservicesshrestartsudochkconfigsshon# 新方式(systemctl)sudosystemctl startsshsudosystemctl stopsshsudosystemctl restartsshsudosystemctlenablessh# 如果脚本中使用了 service 命令# 可以创建别名兼容sudoln-s/bin/systemctl /usr/local/bin/service# 注意:这不是完美的兼容,但大多数常用操作可以工作

故障排查

# 问题1:service 命令找不到# 解决:安装sudoaptinstallinit-system-helpers# 问题2:service 启动失败# 解决:查看详细日志sudojournalctl-xe# 问题3:服务无法启动# 手动运行服务可执行文件,查看错误sudo/usr/sbin/sshd-t# 测试 SSH 配置sudoapachectl configtest# 测试 Apache 配置# 问题4:服务启动后立刻退出# 解决:查看服务日志sudojournalctl-uservice_name-n50

总结

核心价值service是 SysV init 系统的服务管理工具,现代 systemd 系统应使用systemctl

最佳实践

  1. 新系统使用systemctl替代service
  2. 旧脚本兼容性:大多数service命令在 systemd 系统上仍能工作(通过兼容脚本)
  3. 查看服务状态时,使用systemctl status可以看到更详细的信息

常用组合

  • service name start/stop/restart/status:旧方式
  • systemctl start/stop/restart/status name:新方式(推荐)

⚠️ 注意service命令在 systemd 系统上通常只是systemctl的包装器,行为可能略有不同。