在 CentOS 上启动 Node.js 服务,常见有以下几种方式,从“最简单”到“生产推荐”依次说明。
node app.js
⚠️ 缺点:
nohupnohup node app.js > app.log 2>&1 &
查看进程:
ps -ef | grep node
停止服务:
kill -9 进程ID
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
✅ 适合:
vim /etc/systemd/system/nodeapp.service
示例内容:
[Unit]
Description=Node.js App
After=network.target
[Service]
ExecStart=/usr/bin/node /root/app/app.js
WorkingDirectory=/root/app
User=root
Restart=always
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start nodeapp
systemctl enable nodeapp
查看状态:
systemctl status nodeapp
CentOS 自带 node 可能很老:
node -v
建议使用 nvm 安装新版本:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
nvm install 18
firewall-cmd --zone=public --add-port=3000/tcp --permanent
firewall-cmd --reload
| 场景 | 推荐方式 |
|---|---|
| 本地测试 | node app.js |
| 临时后台 | nohup |
| 生产环境 | ✅ PM2 |
| 系统级服务 | systemd |
如果你愿意,可以告诉我:
我可以给你一份完整可直接用的配置。