在 CentOS 上配置 Node.js,有几个常见坑点和最佳实践需要注意,下面按「安装方式 → 版本管理 → 权限 → 服务化 → 性能与安全」给你梳理一下。
yum install nodejs
原因:
curl -sL https://rpm.nodesource.com/setup_18.x | bash -
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
优点:
❌ 错误示例:
node app.js # root 用户
✅ 正确做法:
useradd nodeuser
su nodeuser
node app.js
EACCES: permission denied
npm config set prefix ~/.npm-global
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
或(不推荐但常见):
sudo npm install -g xxx
npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
# /etc/systemd/system/node.service
[Unit]
Description=Node App
After=network.target
[Service]
User=nodeuser
WorkingDirectory=/opt/app
ExecStart=/usr/bin/node app.js
Restart=always
[Install]
WantedBy=multi-user.target
systemctl enable node
systemctl start node
CentOS 默认 firewalld:
firewall-cmd --add-port=3000/tcp --permanent
firewall-cmd --reload
如用云服务器,还要在安全组放行端口。
如果 Node 无法绑定端口或读文件:
getenforce
临时关闭(测试):
setenforce 0
生产建议:
NODE_ENV=productionexport NODE_ENV=production
| 问题 | 原因 |
|---|---|
| node 版本太低 | yum 安装 |
| EACCES | 全局包权限 |
| 端口不通 | 防火墙/安全组 |
| 服务重启丢失 | 没用 PM2/systemd |
| root 跑服务 | 安全隐患 |
如果你愿意,可以告诉我:
我可以直接给你一套完整配置方案。