在 CentOS 上启动 Node.js 程序,常见有几种方式,从简单直接到生产环境推荐依次如下:
node -v
npm -v
如果没有安装:
# 使用 NodeSource(推荐)
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
node app.js
✅ 缺点:
nohupnohup node app.js > app.log 2>&1 &
查看进程:
ps -ef | grep node
停止程序:
kill -9 PID
npm install -g pm2
pm2 start app.js
pm2 list # 查看进程
pm2 logs # 查看日志
pm2 restart app # 重启
pm2 stop app # 停止
pm2 delete app # 删除
pm2 startup
pm2 save
✅ 优点:
sudo vi /etc/systemd/system/nodeapp.service
内容示例:
[Unit]
Description=Node.js App
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/nodeapp
ExecStart=/usr/bin/node /opt/nodeapp/app.js
Restart=always
[Install]
WantedBy=multi-user.target
⚠️ 注意:
WorkingDirectory改成你的项目目录ExecStart用which node确认路径
sudo systemctl daemon-reload
sudo systemctl start nodeapp
sudo systemctl enable nodeapp
systemctl status nodeapp
| 场景 | 推荐方式 |
|---|---|
| 本地测试 | node app.js |
| 临时后台 | nohup |
| 生产环境 | ✅ PM2 |
| 系统级服务 | systemd |
如果你愿意,可以告诉我:
package.json我可以给你完全定制的一套启动方案。