在 CentOS 上搭建 Node.js 环境,常见且推荐的方式有以下几种。下面从最常用、最稳妥的方法开始讲解,适合服务器生产环境。
适合:CentOS 7 / 8 / Stream 优点:版本新、管理方便、稳定
sudo yum install -y curl
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
其他版本可替换:
16.x20.xsudo yum install -y nodejs
node -v
npm -v
适合:开发环境 / 需要多个 Node 版本
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
加载环境:
source ~/.bashrc
nvm install 18
nvm use 18
nvm alias default 18
CentOS 自带源中的 Node.js 版本较老。
sudo yum install -y nodejs npm
查看版本:
node -v
⚠️ 通常版本较低,不建议生产环境使用。
npm config set registry https://registry.npmmirror.com
npm config get registry
如果 Node 监听端口(如 3000):
sudo firewall-cmd --add-port=3000/tcp --permanent
sudo firewall-cmd --reload
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 反向代理
which node
不要使用 root 直接运行 npm,建议:
sudo chown -R $USER:$USER ~/.npm
如果你愿意,可以告诉我:
我可以给你一套完整部署方案。