温馨提示×

centos如何搭建nodejs

小樊
42
2026-07-20 00:06:54
栏目: 编程语言

CentOS 上搭建 Node.js 常见有两种方式:官方二进制包NVM(推荐)。下面按常用场景给你详细说明。


一、方式一:使用 NVM 安装(✅ 推荐)

优点:多版本共存、切换方便,适合开发和生产。

1. 安装依赖

yum install -y curl wget git

2. 安装 NVM

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

加载环境变量:

source ~/.bashrc

3. 查看可安装版本

nvm list-remote

4. 安装 Node.js(示例:LTS 版本)

nvm install --lts

或指定版本:

nvm install 18.19.0

5. 验证

node -v
npm -v

6. 设置默认版本

nvm alias default 18

二、方式二:使用 NodeSource 官方 RPM(适合生产环境)

1. 安装依赖

yum install -y gcc-c++ make

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

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

3. 安装 Node.js

yum install -y nodejs

4. 验证

node -v
npm -v

三、方式三:手动下载二进制包(不推荐)

wget https://nodejs.org/dist/v18.19.0/node-v18.19.0-linux-x64.tar.xz
tar -xJf node-v18.19.0-linux-x64.tar.xz
mv node-v18.19.0-linux-x64 /usr/local/node

配置环境变量:

echo 'export PATH=/usr/local/node/bin:$PATH' >> /etc/profile
source /etc/profile

四、配置 npm(可选但推荐)

1. 设置国内镜像

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

2. 升级 npm

npm install -g npm

五、测试 Node.js 服务

mkdir test && cd test
npm init -y

创建 app.js

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

运行:

node app.js

访问:

http://服务器IP:3000

六、常见问题

1. 防火墙放行端口

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

2. CentOS 7 已停止维护

建议使用:

  • CentOS Stream 8 / 9
  • Rocky Linux / AlmaLinux

七、推荐方案总结

场景 推荐方式
开发环境 ✅ NVM
生产环境 NodeSource
多版本切换 NVM

如果你告诉我:

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

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

0