在 CentOS 上配置 Node.js 时,有几个关键点需要注意,避免常见坑:
不推荐直接用 yum install nodejs(版本通常很旧)。
推荐方式:
curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
yum install -y nodejs
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
nvm install 18
不要用 root 直接跑 npm install -g,否则容易出权限错误。
建议:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH
firewall-cmd --add-port=3000/tcp --permanent
firewall-cmd --reload
不要直接用 node app.js 跑生产服务。
推荐:
npm i -g pm2
pm2 start app.js
pm2 save
pm2 startup
systemd 管理[Unit]
Description=Node App
After=network.target
[Service]
User=nodeuser
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/node app.js
Restart=always
[Install]
WantedBy=multi-user.target
Node 默认有内存限制(约 1.5–2G):
node --max-old-space-size=4096 app.js
如果你说明是 开发环境还是生产环境、CentOS 几、Node 用途,我可以给你更具体的配置方案。