在 CentOS 上让 Node.js 应用开机启动,常见有几种方式,取决于你的 CentOS 版本(CentOS 6 用 init.d,CentOS 7+ 用 systemd)。下面以 CentOS 7 / 8(systemd) 为例,最推荐这种方式。
假设你的 Node 项目在:
/opt/myapp/app.js
sudo vi /etc/systemd/system/nodeapp.service
内容示例(根据实际情况修改):
[Unit]
Description=Node.js App
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/app.js
Restart=on-failure
[Install]
WantedBy=multi-user.target
说明:
ExecStart:node 的绝对路径(可用which node查看)User:建议用非 root 用户(如nodeuser)Restart:崩溃自动重启
sudo systemctl daemon-reload
sudo systemctl start nodeapp
sudo systemctl enable nodeapp
systemctl status nodeapp
npm install -g pm2
pm2 start /opt/myapp/app.js --name myapp
pm2 startup
pm2 save
CentOS 7+ 会自动生成 systemd 服务
创建脚本:
vi /etc/init.d/nodeapp
示例:
#!/bin/bash
# chkconfig: 2345 90 10
# description: node app
case "$1" in
start)
/usr/bin/node /opt/myapp/app.js &
;;
stop)
pkill node
;;
esac
exit 0
chmod +x /etc/init.d/nodeapp
chkconfig nodeapp on
journalctl -u nodeapp如果你愿意,可以告诉我:
我可以给你一份完全适配你环境的配置。