温馨提示×

centos nodejs权限怎么配

小樊
38
2026-09-18 00:15:16
栏目: 编程语言

在 CentOS 上配置 Node.js 的“权限”,通常分为几种常见场景。下面按最常见需求给你一套实用方案。


一、用非 root 用户运行 Node.js(推荐)

不要用 root 直接跑 Node 服务,这是最常见的安全配置。

1. 创建专用用户

useradd -m nodeuser
passwd nodeuser

2. 把项目目录授权给该用户

chown -R nodeuser:nodeuser /var/www/your-node-app
chmod -R 755 /var/www/your-node-app

3. 用该用户启动

su nodeuser
cd /var/www/your-node-app
node app.js

二、监听 80 / 443 端口(非 root 解决方案)

Node 默认不能绑定 <1024 端口(如 80)。

方案 1:用 Nginx 反向代理(最推荐)

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

Node 跑在 3000,Nginx 用 root 跑 80。


方案 2:给 node 绑定端口权限(不推荐)

setcap CAP_NET_BIND_SERVICE=+eip /usr/bin/node

⚠️ 有安全风险,仅测试用。


三、使用 systemd 配置权限(生产推荐)

示例 service 文件

[Unit]
Description=Node.js App
After=network.target

[Service]
User=nodeuser
WorkingDirectory=/var/www/your-node-app
ExecStart=/usr/bin/node app.js
Restart=always

[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start yourapp
systemctl enable yourapp

四、目录和文件权限建议

chmod 755 目录
chmod 644 文件
chmod 600 .env   # 配置文件

五、npm 全局安装权限问题

错误示例

npm install -g xxx
# Error: EACCES

正确做法(不用 sudo)

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

六、SELinux 相关(CentOS 特有)

如果 Node 起不来且日志有 Permission denied

getenforce

临时关闭测试:

setenforce 0

正式环境应配置策略,而不是关 SELinux。


七、常见错误速查

问题 原因
EACCES 用户无权访问目录
port in use 端口被占用
cannot bind 80 非 root 用户
Permission denied (selinux) SELinux 限制

如果你能说清楚:

  • 本地开发 / 服务器部署
  • 是否用 PM2 / Docker / Nginx
  • 报错信息是什么

我可以直接给你一条最合适的配置命令。

0