react前后端分离如何部署
部署 React 前后端分离项目的步骤
前端部署(React)
将 React 项目构建为静态文件,使用 npm run build 生成 build 文件夹。部署到静态服务器如 Nginx、Apache 或托管服务(Vercel、Netlify、GitHub Pages)。
配置 Nginx 代理,确保所有请求指向 index.html 并处理 API 转发:
server {
listen 80;
server_name yourdomain.com;
root /path/to/react/build;
index index.html;
location / {
try_files $uri /index.html;
}
location /api {
proxy_pass http://backend-server:port;
}
}
后端部署
后端服务(如 Node.js、Spring Boot、Django)需独立部署到服务器或云平台(AWS、Azure、Heroku)。确保开放正确的端口,并配置 CORS 允许前端域名访问。
使用 PM2(Node.js)或 Gunicorn(Python)等工具管理进程:

pm2 start server.js
数据库与环境变量
数据库(MySQL、PostgreSQL、MongoDB)需单独部署,确保后端配置正确的连接字符串。环境变量(如 API 密钥、数据库 URL)通过 .env 或云平台配置注入。
HTTPS 与域名
使用 Let’s Encrypt 生成 SSL 证书,配置 Nginx 启用 HTTPS:

server {
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 其他配置同上
}
CI/CD 自动化
通过 GitHub Actions、GitLab CI 或 Jenkins 实现自动化部署。示例 GitHub Actions 配置:
name: Deploy React
on: push
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install && npm run build
- uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./build
跨域问题处理
后端需设置 CORS 头部允许前端域名。例如 Node.js 使用 cors 中间件:
const cors = require('cors');
app.use(cors({ origin: 'https://yourfrontend.com' }));
负载均衡与扩展
高流量场景下,使用负载均衡(如 AWS ALB)横向扩展后端服务,静态文件通过 CDN(如 Cloudflare)加速分发。
监控与日志
部署监控工具(Prometheus、Sentry)和日志系统(ELK Stack)跟踪性能及错误。





