使用Nginx部署前后端分离项目
使用Nginx部署前后端分离项目:用户中心系统实践指南
部署前的关键准备
在正式部署前,务必确保前后端在生产环境能正常运行:
- 前端:测试所有API请求路径和生产环境配置
- 后端:验证数据库连接、环境变量和外部服务集成
- 完整流程测试:执行核心业务场景的端到端测试
重要提示:生产环境问题排查成本远高于测试阶段,请务必完成充分验证
前端部署实战
1. 生产环境配置
修改前端请求基地址(示例使用example.com
,实际替换为你的域名/IP):
// src/plugins/globalRequest.ts
const request = extend({credentials: 'include',prefix: process.env.NODE_ENV === 'production' ? 'https://example.com' // 生产环境地址: undefined // 开发环境使用代理
});
2. 构建与验证
npm run build # 生成dist目录
cd dist
npx serve -s # 启动静态服务器# 浏览器中打开http://localhost:3000
# 检查网络请求是否指向生产环境地址
3. 服务器部署
# 上传到服务器(替换your_user@server_ip)
scp dist.zip your_user@server_ip:/deploy/path# 服务器操作
unzip dist.zip -d user-center-front # 解压到指定目录
4. Nginx配置
# /etc/nginx/conf.d/user-center.conf
server {listen 80;server_name example.com; # 你的域名或IP# 前端静态资源location / {root /deploy/user-center-front;index index.html;try_files $uri $uri/ /index.html; # 支持前端路由}# 后端API代理location /api/ {proxy_pass http://localhost:8080/; # 后端服务地址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_connect_timeout 60s;}# 开启Gzip压缩gzip on;gzip_types text/plain application/javascript application/xml;
}
5. 启动Nginx服务
systemctl enable nginx # 设置开机自启
systemctl restart nginx # 重启服务# 验证端口
ss -tulpn | grep 80
后端部署实战
1. 环境准备
# 安装JDK8
yum install -y java-1.8.0-openjdk-devel# 安装Maven
wget https://dlcdn.apache.org/maven/maven-3/3.8.6/binaries/apache-maven-3.8.6-bin.tar.gz
tar -zxvf apache-maven-3.8.6-bin.tar.gz
mv apache-maven-3.8.6 /opt/maven
2. 项目打包
在IDEA中执行Maven打包命令:
mvn clean package -DskipTests
生成文件:target/user-center-backend-0.0.1-SNAPSHOT.jar
3. 本地验证
java -jar user-center-backend-0.0.1-SNAPSHOT.jar \--spring.profiles.active=prod
连接前端进行集成测试
4. 服务器部署
# 上传JAR文件,直接手拖# 服务器启动(生产环境)
nohup java -jar user-center-backend-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod & # 验证进程
pgrep -f user-center-backend
部署后验证清单
- 前端访问:
https://example.com
是否正常加载 - API测试:在前端执行需要后端交互的操作
- 日志检查:
tail -f /var/log/nginx/error.log # Nginx错误日志 tail -f backend.log # 应用日志
- 端口验证:
ss -tulpn | grep -E '80|8080'
性能优化建议
-
前端静态资源:
location ~* \.(js|css|png)$ {expires 365d;add_header Cache-Control "public"; }
-
后端进程管理:
# 使用systemd服务 [Unit] Description=User Center Backend After=network.target[Service] ExecStart=/usr/bin/java -jar /deploy/backend/app.jar User=appuser Restart=always[Install] WantedBy=multi-user.target