下面给你一份在 CentOS 上搭建 Node.js 的完整常见方案,从简单到推荐,按你需求选即可。
适合:生产环境 / 想用较新 Node.js
sudo yum update -y
sudo yum install -y curl
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
可选版本:
sudo yum install -y nodejs
node -v
npm -v
⚠️ CentOS 7 默认源 Node.js 版本很旧(v6 / v8)
sudo yum install -y nodejs npm
查看版本:
node -v
✅ 适合:临时测试、不关心版本
适合:开发环境 / 一台机器多个 Node 版本
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
重新加载 shell:
source ~/.bashrc
nvm install 18
nvm use 18
nvm alias default 18
node -v
npm -v
npm config set registry https://registry.npmmirror.com
npm install -g pm2
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 at http://localhost:3000');
});
运行:
node app.js
访问:
http://服务器IP:3000
| 系统 | 说明 |
|---|---|
| CentOS 7 | 官方支持已结束,建议用 NodeSource 或 nvm |
| CentOS 8 | 已 EOL,建议迁移到 Rocky / AlmaLinux |
| 防火墙 | 记得放行端口 |
sudo firewall-cmd --add-port=3000/tcp --permanent
sudo firewall-cmd --reload
✅ 生产环境:NodeSource
✅ 开发 / 多版本:nvm
❌ 不推荐:yum 默认源
如果你愿意,可以告诉我:
我可以直接给你一套完整部署方案。