CentOS 进程启动脚本编辑位置与方式
按系统版本选择编辑位置
- CentOS 7/8/9(systemd):编辑或新增服务单元文件 /usr/lib/systemd/system/xxx.service(系统级)或 ~/.config/systemd/user/xxx.service(用户级)。完成后执行 systemctl daemon-reload,用 systemctl enable/start/status xxx.service 管理。示例单元文件见下文。
- CentOS 6(SysV init):编辑 /etc/init.d/xxx(自定义脚本)并用 chkconfig --add xxx 加入开机启动;或直接编辑 /etc/rc.d/rc.local 在 exit 0 前添加要执行的命令或脚本全路径。
systemd 服务文件位置与最小示例
- 编辑文件:sudo vim /usr/lib/systemd/system/myapp.service
- 最小可用示例(Type=simple 前台进程;如为守护进程可用 Type=forking 并配 PIDFile):
[Unit]
Description=My Application
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/myapp.sh
Restart=on-failure
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable myapp.service
sudo systemctl start myapp.service
sudo systemctl status myapp.service
- 说明:服务单元文件以 .service 结尾,分为 [Unit]、[Service]、[Install] 三部分;[Service] 中的 ExecStart/ExecStop/ExecReload 等命令应使用绝对路径。
SysV init 脚本位置与 chkconfig 用法
- 将脚本放入 /etc/init.d/,并添加标准 SysV 头部注释,例如:
#!/bin/sh
# chkconfig: 2345 70 30
# description: My custom service
# processname: myapp
chmod +x /etc/init.d/myapp
chkconfig --add myapp
chkconfig myapp on
- 说明:注释中的 2345 表示运行级别,70 为启动顺序,30 为停止顺序;也可直接在 /etc/rc.d/rc.local 中添加脚本全路径实现开机执行(放在 exit 0 之前)。
如何选择
- 新系统(CentOS 7+)优先使用 systemd 服务单元(/usr/lib/systemd/system/),便于依赖管理、日志与开机顺序控制;传统方式(/etc/init.d/ 与 rc.local)在 CentOS 6 上更常见。