在 CentOS 上搭建 Node.js 常见有两种方式:官方二进制包 和 NVM(推荐)。下面按常用场景给你详细说明。
优点:多版本共存、切换方便,适合开发和生产。
yum install -y curl wget git
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
加载环境变量:
source ~/.bashrc
nvm list-remote
nvm install --lts
或指定版本:
nvm install 18.19.0
node -v
npm -v
nvm alias default 18
yum install -y gcc-c++ make
curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
yum install -y nodejs
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 config set registry https://registry.npmmirror.com
npm install -g npm
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
firewall-cmd --add-port=3000/tcp --permanent
firewall-cmd --reload
建议使用:
| 场景 | 推荐方式 |
|---|---|
| 开发环境 | ✅ NVM |
| 生产环境 | NodeSource |
| 多版本切换 | NVM |
如果你告诉我:
我可以给你一套 完整部署方案。