SysV 到 systemd 怎么对照
存量运维资料大量使用 service 与 chkconfig 写法,新系统实际由 systemd 管理服务。命令可以按固定映射一一对应,行为一致但状态可查性更强。对于仍在 /etc/init.d 下、带 LSB 头的旧启动脚本,systemd 会通过 systemd-sysv-generator 自动生成兼容单元,让老脚本也能被 systemctl 管理和开机自启。理解这层兼容机制,迁移老应用时就不需要先重写启动脚本。
基本信息
| 适用平台 | systemd 系 Linux:RHEL 7+、openEuler、银河麒麟、UOS |
|---|---|
| 兼容层 | systemd-sysv-generator 为 /etc/init.d 下带 LSB 头的脚本生成单元 |
| 状态判断 | 统一用 systemctl is-active、is-enabled |
| 生成单元位置 | /run/systemd/generator.late/ 下的临时单元文件 |
| 原生方案 | 长期维护建议改写 .service,行为更可控 |
典型使用场景
- 老资料迁移:把手册里的 service/chkconfig 命令直接换算成 systemctl
- 旧应用上线:带 init 脚本的第三方程序不重写也能开机自启
- 脚本改造:巡检脚本里依赖 service 返回码的判断改成 is-active
- 排障对比:服务状态异常时确认到底走的生成单元还是原生单元
- 培训授课:用对照表讲清两代工具的关系与差异
命令对照
| SysV 用法 | systemd 对应 | 说明 |
|---|---|---|
| service nginx start | systemctl start nginx | 启动行为一致 |
| service nginx stop | systemctl stop nginx | 停止并回收相关进程 |
| chkconfig nginx on | systemctl enable nginx | 设开机自启 |
| chkconfig nginx off | systemctl disable nginx | 取消自启 |
| chkconfig --list | systemctl list-unit-files --type=service | 看各服务启用状态 |
| /etc/init.d/nginx status | systemctl status nginx | 输出更详细,含最近日志 |
| chkconfig --add myapp | 脚本放 /etc/init.d/ 后 daemon-reload | 由兼容层自动生成单元 |
| runlevel | systemctl get-default | 运行级对应 target |
示例与验证
示例与验证
service nginx status # 旧写法仍可用(兼容层)
systemctl status nginx --no-pager # 推荐写法,含日志片段
systemctl is-active nginx || echo '未运行' # 脚本里判断状态用这个
systemctl is-enabled nginx # 判断是否开机自启
systemctl list-unit-files --type=service | grep -i nginx
ls /run/systemd/generator.late/ | grep myapp # 看兼容层生成的单元
systemctl cat myapp.service # 查看最终生效的单元定义systemd-sysv-generator 只为 /etc/init.d 下带 LSB 头信息的脚本生成单元;没有 LSB 头的脚本不会自动生成,长期维护建议直接写原生 .service。
生成单元与原生单元同名时会冲突,加载到哪一份取决于优先级;迁移时移除多余定义,用 systemctl cat 确认实际生效内容。