一台服务器如何同时部署前端React应用和Node.js后端服务?

在一台服务器上同时部署前端 React 应用和 Node.js 后端服务是常见的全栈部署方式。以下是详细的步骤和最佳实践:


✅ 部署架构概览

用户请求
    ↓
   Nginx(反向X_X)
    ├── /api → 转发到 Node.js 服务(如:localhost:3001)
    └── 其他路径 → 提供 React 静态文件(如:/var/www/react-app)

Node.js 运行后端 API,React 构建为静态文件由 Nginx 托管。


🔧 步骤详解

1. 准备服务器环境(以 Ubuntu 为例)

# 更新系统
sudo apt update && sudo apt upgrade -y

# 安装 Node.js、Nginx、npm
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs nginx git

2. 部署 Node.js 后端服务

a. 上传或克隆代码

cd /var/www
git clone https://your-repo/backend.git node-api
cd node-api
npm install

b. 使用 PM2 管理 Node 进程(推荐)

npm install -g pm2
pm2 start server.js --name "node-api"
pm2 startup
pm2 save

假设你的后端监听 3001 端口:

app.listen(3001, 'localhost', () => {
  console.log('API running on http://localhost:3001');
});

3. 构建并部署 React 前端应用

a. 构建生产版本

cd /var/www
git clone https://your-repo/frontend.git react-app
cd react-app
npm install
npm run build

构建完成后,静态文件位于 build/ 目录。

b. 移动构建文件(可选)

sudo cp -r build /var/www/react-build

4. 配置 Nginx 反向X_X

编辑 Nginx 配置文件:

sudo nano /etc/nginx/sites-available/default

写入以下配置:

server {
    listen 80;
    server_name your-domain.com;  # 或服务器 IP

    # 托管 React 前端
    location / {
        root /var/www/react-build;
        try_files $uri $uri/ /index.html;
    }

    # X_X API 请求到 Node.js 服务
    location /api {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}

检查并重启 Nginx

sudo nginx -t
sudo systemctl reload nginx

5. (可选)配置 HTTPS(使用 Let’s Encrypt)

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com

Certbot 会自动修改 Nginx 配置启用 HTTPS。


📌 注意事项

  1. CORS 处理
    如果前端直接访问 http://localhost:3001/api,需要在开发时处理 CORS。
    生产中通过 Nginx 统一域名,避免跨域问题。

  2. 环境变量管理

    • 前端:构建时注入 REACT_APP_API_URL=/api
    • 后端:使用 .env 文件或 PM2 配置管理环境变量
  3. 安全加固

    • 防火墙开放 80/443,关闭其他端口
    • 使用 ufw 设置防火墙规则
    • 不要以 root 用户运行 Node.js
  4. 自动部署(可选)

    • 使用 GitHub Actions / Jenkins 自动拉取代码、构建、重启服务

✅ 最终效果

  • 访问 https://your-domain.com → 显示 React 应用
  • 请求 https://your-domain.com/api/users → 被 Nginx 转发到 Node.js 后端

💡 总结

组件 技术/工具 作用
前端 React + Nginx 提供静态页面
后端 Node.js + PM2 提供 API 接口
反向X_X Nginx 统一路由、负载均衡、HTTPS
进程管理 PM2 保持 Node.js 永久运行

这样就实现了在同一台服务器上高效、安全地部署前后端应用。

如有具体框架(如 Express、Next.js)或其他需求,可以进一步优化方案。