温馨提示×

centos怎么配置nodejs反向代理

小樊
34
2026-07-08 06:38:04
栏目: 编程语言

CentOS 上配置 Node.js 反向代理,最常用、最稳定的方案是 Nginx 反向代理。下面我用 CentOS 7 / 8 举例,从 Node.js 部署 → Nginx 反向代理 → 防火墙/端口 → 可选 HTTPS 给你一套完整流程。


一、环境准备

1️⃣ 安装 Node.js(已安装可跳过)

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

验证:

node -v
npm -v

二、部署 Node.js 服务

1️⃣ 示例 Node.js 应用

// app.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200);
  res.end('Hello Node.js');
});

server.listen(3000, () => {
  console.log('Server running on port 3000');
});

启动:

node app.js

Node 默认监听 3000 端口


三、安装并配置 Nginx 反向代理

1️⃣ 安装 Nginx

sudo yum install -y nginx

启动并设置开机自启:

sudo systemctl start nginx
sudo systemctl enable nginx

2️⃣ 配置反向代理

编辑配置文件:

sudo vi /etc/nginx/conf.d/node.conf

写入以下内容(重点):

server {
    listen 80;
    server_name yourdomain.com;  # 或服务器公网 IP

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

3️⃣ 检查并重启 Nginx

sudo nginx -t
sudo systemctl restart nginx

访问:

http://服务器IP

✅ 如果看到 Hello Node.js,说明反向代理成功。


四、放行防火墙端口(非常重要)

CentOS 7 / 8

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

或直接放行端口:

sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --reload

五、Node.js 使用进程管理器(推荐)

不要让 node app.js 直接跑,推荐使用 PM2

安装 PM2

sudo npm install -g pm2

启动应用

pm2 start app.js --name node-app
pm2 save
pm2 startup

六、配置 HTTPS(可选但强烈推荐)

使用 Let’s Encrypt

sudo yum install -y certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com

证书会自动配置到 Nginx,并自动续期。


七、反向代理结构总结

浏览器
  ↓
80 / 443 (Nginx)
  ↓
3000 (Node.js)

八、常见问题排查

❌ 502 Bad Gateway

  • Node 没启动
  • 端口不一致
  • SELinux 拦截
getenforce
# 如果是 Enforcing
sudo setenforce 0

九、简化版配置(HTTP 快速示例)

server {
    listen 80;
    server_name _;

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

如果你愿意,我可以帮你:

  • ✅ 写 systemd 服务
  • ✅ 配置 多 Node 负载均衡
  • ✅ 配置 WebSocket 反向代理
  • ✅ 排查 502 / 404 / 跨域问题

直接把你的 CentOS 版本 + Node 端口 + 是否有域名 发我即可。

0