基本部署架构
在典型的 SpringBoot + Vue 前后端分离项目中:
- SpringBoot 提供 API 后端服务
- Vue 提供前端界面
- Nginx 作为反向代理和静态资源服务器
一、 准备工作
前端部分
- 构建 Vue 项目:
npm run build生成dist目录 - 将
dist目录上传到服务器(如/var/www/my-vue-app) - 接口baseUrl:http://localhost/api (localhost替换为你的ip或域名)
后端部分
- 打包 SpringBoot 项目:
mvn package生成 jar 文件 - 上传 jar 文件到服务器(如
/opt/my-springboot-app) - 使用
java -jar启动服务(通常在 8080 端口)
说明:文本仅介绍http协议的部署方式,https大同小异,在此基础添加配置即可。
二、nginx配置
server {
listen 80;
server_name yourdomain.com; # 替换为你的域名或IP
# 定义上游服务器组(后端SpringBoot实例)
upstream backend {
# 默认使用轮询策略
server 127.0.0.1:8080; # 实例1
server 127.0.0.1:8081; # 实例2
server 192.168.1.100:8080; # 其他服务器的实例
}
# 前端静态文件配置
location / {
root /var/www/my-vue-app/dist; # Vue打包后的dist目录
try_files $uri $uri/ /index.html;
index index.html;
}
# 后端API代理配置
location /api/ {
#proxy_pass http://backend/; # 指向upstream组,此行为多服务负载均衡配置
proxy_pass http://localhost:8080/; # SpringBoot服务地址,此行为单一服务配置
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 可选:WebSocket支持
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
# 静态资源缓存配置
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
root /var/www/my-vue-app/dist;
expires 30d;
add_header Cache-Control "public, no-transform";
}
# 错误页面配置
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
其他配置
http {
...
# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 客户端请求配置
client_max_body_size 1000M; # 解决文件上传大小限制
client_body_buffer_size 2M;
client_header_buffer_size 256k;
large_client_header_buffers 4 256k;
# 客户端连接超时配置
client_body_timeout 600s;
client_header_timeout 600s;
keepalive_timeout 120s;
keepalive_requests 1000;
# 反向代理超时配置
proxy_connect_timeout 600s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
}
三、总结
通过以上配置,我们可以使用80端口访问我们的前端页面和和后端接口,然而80端口不用加到ip后面,http协议+ip默认就是80端口,https+ip默认443端口。