Linux service 与 systemctl 区别

1次阅读

Linux service 与 systemctl 区别

service 是传统 SysV init 系统的命令,用于临时启动、停止、重启 SysV 风格的初始化脚本(通常位于 /etc/init.d/);systemctl 是 systemd 的核心管理工具,用于全面控制 unit(服务、定时器、挂载点等),支持依赖管理、状态持久化、日志集成和更精细的状态查询。

作用范围不同

service 只能操作以 shell 脚本形式存在的 SysV 服务(如 /etc/init.d/nginx),不感知依赖、不记录服务生命周期,也不影响开机自启设置。
systemctl 操作的是 systemd unit 文件(如 /lib/systemd/system/nginx.service),可精确控制服务状态、启用/禁用开机自启、查看依赖树、设置资源限制等。

命令行为差异明显

例如重启 Nginx:

  • service nginx restart:直接调用 /etc/init.d/nginx restart,不检查是否已启用、不读取 systemd 配置、不记录到 journal
  • systemctl restart nginx:按 unit 定义执行 Stop + Start 流程,自动处理依赖、触发相关 unit(如 reload nginx-config)、写入 journal 日志

开机自启机制完全不同

service 本身无法设置开机启动。传统上需用 update-rc.ddebian)或 chkconfig(RHEL)修改 runlevel 链接,与当前运行时状态无关。
systemctl 使用 enable/disable 命令,在 /etc/systemd/system/ 创建软链接,真正决定服务是否随系统启动。该设置独立于当前运行状态。

状态查看与排错能力差距大

service nginx status 仅执行脚本内的 status 函数,输出格式不统一,常只返回“running”或“not running”,无详细上下文。
systemctl status nginx 显示完整 unit 状态、激活状态(active/inactive)、子进程树、最近日志片段(来自 journald)、启动耗时、失败原因(如有),极大提升诊断效率。

在已启用 systemd 的现代 linux 发行版中(如 ubuntu 16.04+、centos 7+、Debian 8+),systemctl 是推荐且功能完备的首选工具service 命令只是为兼容旧脚本保留的封装,实际会尝试将请求转发给 systemd(如调用 systemctl start xxx),但语义模糊、行为受限,不应作为日常管理手段。

text=ZqhQzanResources