在 CentOS(7 及以后) 里,给 Node.js 应用配置开机自启,最常见、最推荐的方式是 systemd。下面分步骤说明,包含示例和常见注意事项。
cat /etc/centos-release
node -v
npm -v
/opt/myapp
启动命令是:
node /opt/myapp/app.js
或
npm start
sudo vi /etc/systemd/system/myapp.service
node 直接启动[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=always
RestartSec=5
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
npm start 启动ExecStart=/usr/bin/npm start
⚠️ 注意:
ExecStart必须是 绝对路径- 查看 node 路径:
which node
which npm
sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl enable myapp
systemctl status myapp
# 启动
systemctl start myapp
# 停止
systemctl stop myapp
# 重启
systemctl restart myapp
# 查看日志
journalctl -u myapp -f
# 禁用开机自启
systemctl disable myapp
查看详细日志:
journalctl -u myapp --no-pager
netstat -tunlp | grep 3000
which node
确保 ExecStart 路径一致
如果是 CentOS 6,使用 chkconfig + init.d:
vi /etc/init.d/myapp
chmod +x /etc/init.d/myapp
chkconfig --add myapp
chkconfig myapp on
⚠️ 但 强烈建议升级到 CentOS 7+ 使用 systemd
npm install -g pm2
pm2 start app.js
pm2 startup
pm2 save
✅ 最佳实践
systemdPM2 + systemdsystemctl enable如果你愿意,可以把你的:
npm start发给我,我可以帮你 直接生成可用的 service 文件 ✅