温馨提示×

centos怎么配置nodejs运行

小樊
48
2026-08-29 17:59:43
栏目: 编程语言

下面分几种常见方式,说明 在 CentOS 上配置 Node.js 运行环境,涵盖 安装 → 环境变量 → 运行 → 开机自启 → 生产建议


一、CentOS 版本说明

  • CentOS 7(主流,仍大量使用)
  • CentOS 8 / Stream(已停止维护,建议转 Rocky / Alma)
  • 以下以 CentOS 7 为主,其他版本基本一致

二、安装 Node.js(推荐方式)

✅ 方式一:使用 NodeSource(强烈推荐)

可自由选择版本(如 18.x / 20.x)

1️⃣ 安装准备

sudo yum install -y curl

2️⃣ 添加 NodeSource 源(以 Node 18 为例)

curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -

3️⃣ 安装 Node.js

sudo yum install -y nodejs

4️⃣ 验证

node -v
npm -v

✅ 方式二:使用 EPEL(版本较旧,不推荐)

sudo yum install -y epel-release
sudo yum install -y nodejs

⚠️ 版本可能较老(v10 左右)


✅ 方式三:使用 NVM(适合开发环境)

适合多版本切换

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

加载环境:

source ~/.bashrc

安装 Node:

nvm install 18
nvm use 18

三、配置 Node.js 运行环境

1️⃣ 设置国内 npm 镜像(可选)

npm config set registry https://registry.npmmirror.com

查看:

npm config get registry

2️⃣ 运行 Node.js 程序

示例:

mkdir -p /opt/nodeapp
cd /opt/nodeapp
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
  res.end('Hello Node.js on CentOS');
});
server.listen(3000, () => {
  console.log('Server running on port 3000');
});

运行:

node app.js

访问:

http://服务器IP:3000

四、后台运行 Node.js(生产环境)

✅ 方式一:使用 PM2(强烈推荐)

npm install -g pm2

启动项目:

pm2 start app.js --name nodeapp

常用命令:

pm2 list
pm2 restart nodeapp
pm2 stop nodeapp
pm2 logs

开机自启:

pm2 startup
pm2 save

✅ 方式二:systemd(不依赖 PM2)

创建服务文件

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

启动服务

sudo systemctl daemon-reload
sudo systemctl start nodeapp
sudo systemctl enable nodeapp

查看状态:

systemctl status nodeapp

五、防火墙放行端口(CentOS 7)

sudo firewall-cmd --add-port=3000/tcp --permanent
sudo firewall-cmd --reload

六、常见问题排查

❌ node 命令找不到

which node

如果使用 NVM,确认:

echo $NVM_DIR

❌ 端口被占用

netstat -tunlp | grep 3000

七、生产环境建议 ✅

  • ✅ Node.js ≥ 18 LTS
  • ✅ 使用 PM2
  • ✅ 不要直接用 root 运行业务程序
  • ✅ 配合 Nginx 反向代理
  • ✅ 日志统一管理

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

  • ✅ CentOS 版本
  • ✅ 单项目 / 多项目
  • ✅ 是否用 Nginx
  • ✅ 是否 Docker

我可以给你 完整生产级部署方案

0