在 CentOS 上配置 Node.js 时,常见坑和注意事项如下,按“是否踩坑率”整理:
CentOS 自带 yum 里的 nodejs 版本非常旧(经常是 6.x / 8.x)。
✅ 推荐方式:
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 容易出权限错误。
✅ 建议:
sudo npm -gmkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH
CentOS 默认有 firewalld
firewall-cmd --zone=public --add-port=3000/tcp --permanent
firewall-cmd --reload
云服务器还要放行安全组
如果 Node 端口起不来:
getenforce
可临时关闭测试:
setenforce 0
生产不建议直接关,应配置策略。
不要用 node app.js &
✅ 推荐:
npm i -g pm2
pm2 start app.js
编译原生模块(如 bcrypt、sqlite)时需要:
yum groupinstall "Development Tools"
npm config set registry https://registry.npmmirror.com
[Unit]
Description=Node App
After=network.target
[Service]
User=node
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/node app.js
Restart=always
[Install]
WantedBy=multi-user.target
如果你愿意,可以告诉我:
我可以给你一步到位的具体命令。