部署环境准备

确保服务器已安装 JDK、Node.js、Nginx 和 MySQL(或其他数据库)。JDK 版本需与 Spring Boot 兼容,Node.js 版本需支持 Vue 项目的构建。Nginx 用于反向代理和静态资源托管。

后端部署要点

Spring Boot 项目需打包为 JAR 或 WAR 文件。推荐使用 JAR 包部署,通过 java -jar 命令启动。
配置 application.propertiesapplication.yml 中的数据库连接、端口号等参数,确保与生产环境一致。
使用 nohup 或 PM2 守护进程,避免 SSH 断开后服务终止:

nohup java -jar your-project.jar > springboot.log 2>&1 &

前端部署要点

Vue 项目需通过 npm run build 生成静态文件(默认在 dist 目录)。
dist 目录上传至服务器,通过 Nginx 配置静态资源路径。
检查 vue.config.js 中的 publicPath,确保资源引用路径正确(如设置为 .//子目录/)。

Nginx 配置关键

配置反向代理,将 API 请求转发至 Spring Boot 后端(通常运行在 8080 端口)。
示例配置片段:

server {
    listen 80;
    server_name your-domain.com;

    location / {
        root /path/to/vue/dist;
        index index.html;
        try_files $uri $uri/ /index.html; # 支持 Vue 路由 history 模式
    }

    location /api/ {
        proxy_pass http://localhost:8080/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

跨域与安全

若前端直接访问后端接口,需在 Spring Boot 中配置 CORS:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

生产环境建议限制 allowedOrigins 为具体域名,并启用 HTTPS(通过 Nginx 配置 SSL 证书)。

静态资源缓存

为提升性能,可在 Nginx 中配置静态资源缓存:

location /static/ {
    expires 365d;
    add_header Cache-Control "public";
}

日志与监控

后端日志可通过 Logback 或 Log4j 输出到文件,结合 logrotate 管理日志大小。
前端错误监控可接入 Sentry 或自建日志服务。
使用 htopnetstat 监控服务器资源占用和端口状态。

自动化部署

推荐使用 CI/CD 工具(如 Jenkins、GitLab CI)自动化构建和部署流程。
脚本示例(GitLab CI):

stages:
  - build
  - deploy

build_frontend:
  stage: build
  script:
    - npm install
    - npm run build
  artifacts:
    paths:
      - dist/

deploy_backend:
  stage: deploy
  script:
    - scp target/*.jar user@server:/path/to/deploy
    - ssh user@server "systemctl restart springboot-service"

常见问题排查

前端 404 错误:检查 Nginx try_files 配置及 publicPath
接口 502 错误:确认后端服务是否运行,端口是否被占用。
静态资源加载失败:检查路径是否正确,Nginx 是否有读写权限。

更多推荐