在 CentOS 上配置 Node.js,常见方式有 官方源 / NVM / 二进制包 三种。下面从最推荐到最灵活依次说明,并包含常见配置项。
sudo yum install -y curl gcc-c++ make
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
node -v
npm -v
✅ 优点:
yum updatecurl -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
node -v
npm -v
✅ 优点:
cd /usr/local
sudo wget https://nodejs.org/dist/v18.20.4/node-v18.20.4-linux-x64.tar.xz
sudo tar -xvf node-v18.20.4-linux-x64.tar.xz
echo 'export PATH=/usr/local/node-v18.20.4-linux-x64/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
node -v
npm -v
npm config set registry https://registry.npmmirror.com
查看:
npm config get registry
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
export NODE_ENV=production
永久生效:
echo 'export NODE_ENV=production' >> /etc/profile
source /etc/profile
node --max-old-space-size=4096 app.js
或写入环境变量:
export NODE_OPTIONS="--max-old-space-size=4096"
| 系统 | 说明 |
|---|---|
| CentOS 7 | 默认 gcc 较老,建议用 NodeSource |
| CentOS 8 | 已 EOL,建议迁移到 Rocky / Alma |
| firewalld | Node 端口需放行 |
firewall-cmd --add-port=3000/tcp --permanent
firewall-cmd --reload
✅ CentOS + NodeSource + PM2
npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
我可以给你 一套完整可用的最小配置方案。