温馨提示×

centos nodejs配置要注意什么

小樊
41
2026-09-21 03:04:36
栏目: 编程语言

在 CentOS 上配置 Node.js,有几个常见坑点和最佳实践需要注意,下面按「安装方式 → 版本管理 → 权限 → 服务化 → 性能与安全」给你梳理一下。


一、安装方式选择(很重要)

❌ 不推荐

yum install nodejs

原因:

  • CentOS 官方源 Node 版本非常旧(通常是 10.x 甚至更老)
  • 难以升级,容易踩坑

✅ 推荐方式 1:NodeSource(最常用)

curl -sL https://rpm.nodesource.com/setup_18.x | bash -
yum install -y nodejs

检查:

node -v
npm -v

✅ 推荐方式 2:nvm(开发环境首选)

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 18
nvm use 18

优点:

  • 多版本切换
  • 不污染系统环境

二、不要使用 root 跑 Node 服务(安全)

❌ 错误示例:

node app.js   # root 用户

✅ 正确做法:

useradd nodeuser
su nodeuser
node app.js

三、npm 全局包权限问题(CentOS 常见)

报错示例

EACCES: permission denied

解决方案(推荐)

npm config set prefix ~/.npm-global
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

或(不推荐但常见):

sudo npm install -g xxx

四、Node 服务进程管理(生产必做)

✅ 使用 PM2(最常用)

npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup

或用 systemd(CentOS 原生)

# /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

如用云服务器,还要在安全组放行端口。


六、SELinux(CentOS 特有坑)

如果 Node 无法绑定端口或读文件:

getenforce

临时关闭(测试):

setenforce 0

生产建议:

  • 配置 SELinux 策略
  • 或设置正确 context(不要直接禁用)

七、性能 & 生产建议

  • 使用 Nginx 反向代理
  • 开启 gzip
  • 使用 cluster 或 PM2 多进程
  • 设置 NODE_ENV=production
export NODE_ENV=production

八、常见错误总结

问题 原因
node 版本太低 yum 安装
EACCES 全局包权限
端口不通 防火墙/安全组
服务重启丢失 没用 PM2/systemd
root 跑服务 安全隐患

如果你愿意,可以告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • 用途(开发 / 生产 / 学习)
  • 是否用 Docker

我可以直接给你一套完整配置方案

0