在 CentOS 上配置 Node.js 通常有几种常见方式,下面按推荐程度给你说明,你可以根据自己的需求选择。
以 Node.js 18.x 为例(也可换成 20.x、16.x):
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
node -v
npm -v
✅ 适合:生产环境 / 开发环境
可以多版本切换,不影响系统环境。
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
✅ 适合:前端 / 后端开发、多项目
版本较旧:
sudo yum install -y nodejs npm
⚠️ CentOS 7 默认 Node 版本很低(如 6.x / 8.x)
npm config set registry https://registry.npmmirror.com
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
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
sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --reload
建议使用:
如果你能告诉我:
我可以给你更精准的配置方案(包括 PM2、Nginx 反向代理等)。