使用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