温馨提示×

centos怎样启动nodejs服务

小樊
43
2026-09-14 23:15:47
栏目: 编程语言

在 CentOS 上启动 Node.js 服务,一般有以下几种常见方式,从简单到生产级逐步说明。


一、最基础方式(测试用)

1. 安装 Node.js

# 使用 NodeSource(推荐)
curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
yum install -y nodejs

# 验证
node -v
npm -v

2. 启动 Node.js 服务

假设你的入口文件是 app.js

cd /path/to/project
node app.js

⚠️ 这种方式:

  • 关闭终端就会停止
  • 不适合生产环境

二、后台运行(不推荐长期使用)

node app.js &

nohup node app.js > app.log 2>&1 &

查看进程:

ps aux | grep node

三、使用 PM2(强烈推荐 ✅)

1. 安装 PM2

npm install -g pm2

2. 启动服务

pm2 start app.js

3. 常用命令

pm2 list
pm2 logs
pm2 restart app
pm2 stop app
pm2 delete app

4. 开机自启

pm2 startup
pm2 save

✅ 优点:

  • 自动重启
  • 日志管理
  • 开机自启
  • 多进程支持

四、使用 systemd(生产服务器推荐)

1. 创建服务文件

vim /etc/systemd/system/node.service

示例内容:

[Unit]
Description=Node.js Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/path/to/project
ExecStart=/usr/bin/node /path/to/project/app.js
Restart=on-failure

[Install]
WantedBy=multi-user.target

2. 启动服务

systemctl daemon-reload
systemctl start node
systemctl enable node

3. 查看状态

systemctl status node
journalctl -u node -f

五、结合 Nginx(常见生产架构)

用户 → Nginx(80) → Node.js(3000)

Nginx 示例配置:

location / {
    proxy_pass http://127.0.0.1:3000;
}

总结建议

场景 推荐方式
本地测试 node app.js
小型服务 PM2
生产服务器 systemd + Nginx
高可用 PM2 + Nginx

如果你愿意,可以告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • Node 版本
  • 是否是 Web 服务(Express / Koa / Nest)

我可以直接帮你写完整配置。

0