温馨提示×

centos如何搭建nodejs配置

小樊
45
2026-08-29 17:29:41
栏目: 编程语言

CentOS 上搭建 Node.js 环境,常见且推荐的方式有以下几种。下面从最常用、最稳妥的方法开始讲解,适合服务器生产环境。


一、使用 NodeSource 安装(✅ 推荐)

适合:CentOS 7 / 8 / Stream 优点:版本新、管理方便、稳定

1️⃣ 安装依赖

sudo yum install -y curl

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

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

其他版本可替换:

  • 16.x
  • 20.x

3️⃣ 安装 Node.js

sudo yum install -y nodejs

4️⃣ 验证安装

node -v
npm -v

二、使用 NVM 安装(✅ 开发/多版本推荐)

适合:开发环境 / 需要多个 Node 版本

1️⃣ 安装 NVM

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

加载环境:

source ~/.bashrc

2️⃣ 安装 Node.js

nvm install 18
nvm use 18

3️⃣ 设置默认版本

nvm alias default 18

三、使用 yum 安装(❌ 不推荐)

CentOS 自带源中的 Node.js 版本较老。

sudo yum install -y nodejs npm

查看版本:

node -v

⚠️ 通常版本较低,不建议生产环境使用。


四、配置 npm(国内加速)

1️⃣ 使用淘宝镜像

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

2️⃣ 验证

npm config get registry

五、防火墙 & 端口(运行 Node 服务必看)

如果 Node 监听端口(如 3000):

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

六、示例:运行一个 Node 服务

mkdir test-node
cd test-node
npm init -y

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

七、生产环境建议

✅ 使用 NodeSource + PM2

npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup

✅ 可配合 Nginx 反向代理


八、常见问题

❓ 找不到 node 命令

which node

❓ 权限问题

不要使用 root 直接运行 npm,建议:

sudo chown -R $USER:$USER ~/.npm

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

  • ✅ CentOS 版本(7 / 8 / Stream)
  • ✅ 是否用于生产环境
  • ✅ 是否需要 Nginx + HTTPS

我可以给你一套完整部署方案

0