温馨提示×

centos nodejs怎样配置

小樊
41
2026-09-08 20:55:35
栏目: 编程语言

CentOS 上配置 Node.js 通常有几种常见方式,下面按推荐程度给你说明,你可以根据自己的需求选择。


一、使用 NodeSource 安装(✅ 推荐,版本新、简单)

1. 添加 NodeSource 仓库

Node.js 18.x 为例(也可换成 20.x、16.x):

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

2. 安装 Node.js

sudo yum install -y nodejs

3. 验证

node -v
npm -v

✅ 适合:生产环境 / 开发环境


二、使用 NVM 安装(✅ 推荐用于开发)

可以多版本切换,不影响系统环境。

1. 安装 NVM

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

2. 加载 NVM

source ~/.bashrc

3. 安装 Node.js

nvm install 18
nvm use 18

4. 设置默认版本

nvm alias default 18

✅ 适合:前端 / 后端开发、多项目


三、使用 CentOS 自带 yum(❌ 不推荐)

版本较旧:

sudo yum install -y nodejs npm

⚠️ CentOS 7 默认 Node 版本很低(如 6.x / 8.x)


四、基础环境配置(常用)

1. 设置 npm 镜像(国内加速)

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

2. 全局安装目录(可选)

mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

五、运行一个简单的 Node 服务

mkdir test && cd test
npm init -y

app.js

const http = require('http');
http.createServer((req, res) => {
  res.end('Hello CentOS Node.js');
}).listen(3000);

运行:

node app.js

访问:

http://服务器IP:3000

六、常见问题

1. 端口无法访问

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

2. CentOS 8 已停止维护

建议使用:

  • CentOS Stream
  • Rocky Linux
  • AlmaLinux

如果你能告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • 用途(前端 / 后端 / 生产 / 学习)

我可以给你更精准的配置方案(包括 PM2、Nginx 反向代理等)。

0