在云服务器上部署SpringBoot+Vue前后端分离项目

在云服务器上部署SpringBoot+Vue前后端分离项目

一、部署前准备

1.1 环境要求

在开始部署之前,需要确保云服务器已安装以下环境组件:

后端环境:

  • JDK 1.8+(推荐JDK 17)
  • MySQL 5.7+ 或 8.0
  • Redis(可选,推荐6.0+)

前端环境:

  • Nginx 1.20+
  • Node.js 16+(用于前端打包)

1.2 服务器配置

端口放行策略:

  • 宝塔面板:8888/888
  • 后端服务:8080/9090(根据实际配置)
  • 数据库:3306
  • 前端服务:80/443
  • Redis:6379

安全组配置:

在云服务器控制台的安全组中,需要放行上述端口。以阿里云为例,进入ECS控制台→安全组→配置规则,添加相应的入方向规则。

二、后端SpringBoot项目部署

2.1 项目打包

方式一:使用Maven打包(推荐)

在项目根目录执行以下命令:

mvn clean package -Dmaven.test.skip=true

打包完成后,在target目录下会生成可执行的JAR文件,如springboot-0.0.1-SNAPSHOT.jar

方式二:使用IDEA打包

  1. 打开IDEA右侧的Maven面板
  2. 依次执行cleanpackage命令
  3. 生成的JAR文件位于target目录

2.2 数据库配置

创建数据库:

CREATE DATABASE your_database;
CREATE USER 'your_user'@'%' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON your_database.* TO 'your_user'@'%';
FLUSH PRIVILEGES;

导入SQL文件:

mysql -u root -p your_database < your_database.sql

2.3 配置文件修改

application.ymlapplication.properties中配置生产环境参数:

server:
  port: 8080
  servlet:
    context-path: /api

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: your_user
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver

  redis:
    host: localhost
    port: 6379
    password: your_redis_password

2.4 上传并启动服务

上传JAR包到服务器:

scp target/your-project.jar root@your-server-ip:/www/wwwroot/backend/

启动服务:

# 后台启动并输出日志
nohup java -jar your-project.jar > app.log 2>&1 &

# 查看启动日志
tail -f app.log

# 查看进程
ps -ef | grep java

# 停止服务
kill -9 进程ID

使用systemd管理服务(推荐):

创建服务配置文件/etc/systemd/system/your-service.service

[Unit]
Description=Your SpringBoot Service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/bin/java -jar /www/wwwroot/backend/your-project.jar
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

启动服务:

systemctl daemon-reload
systemctl start your-service
systemctl enable your-service
systemctl status your-service

三、前端Vue项目部署

3.1 项目打包

配置生产环境:

vue.config.js中配置:

module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/' : '/',
  outputDir: 'dist',
  assetsDir: 'static',
  devServer: {
    proxy: {
      '/api': {
        target: 'http://your-server-ip:8080',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

执行打包命令:

npm run build

打包完成后会生成dist目录,包含所有静态资源文件。

3.2 Nginx安装与配置

安装Nginx:

# CentOS/RHEL
sudo yum install nginx

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install nginx

配置Nginx:

编辑配置文件/etc/nginx/nginx.conf/etc/nginx/sites-available/default

server {
    listen 80;
    server_name your-domain.com your-server-ip;
    
    # 前端静态资源
    location / {
        root /www/wwwroot/frontend/dist;
        index index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    
    # 后端API代理
    location /api/ {
        proxy_pass http://127.0.0.1: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_set_header X-Forwarded-Proto $scheme;
        
        # 解决跨域问题
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
        add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        
        if ($request_method = 'OPTIONS') {
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
            add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header Access-Control-Max-Age 1728000;
            add_header Content-Type 'text/plain; charset=utf-8';
            add_header Content-Length 0;
            return 204;
        }
    }
    
    # 静态资源缓存
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        root /www/wwwroot/frontend/dist;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

测试并重载配置:

# 检查配置语法
nginx -t

# 重载配置
nginx -s reload

# 重启Nginx
systemctl restart nginx

3.3 上传前端文件

将打包后的dist目录上传到服务器:

scp -r dist root@your-server-ip:/www/wwwroot/frontend/

设置目录权限:

chown -R www-data:www-data /www/wwwroot/frontend
chmod -R 755 /www/wwwroot/frontend

四、跨域问题解决方案

4.1 后端解决方案(推荐)

方式一:全局跨域配置类

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

方式二:过滤器方式

@Configuration
public class CorsFilterConfig {
    
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        
        return new CorsFilter(source);
    }
}

4.2 前端解决方案

方式一:开发环境代理(Vue CLI)

// vue.config.js
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

方式二:生产环境Nginx代理

见3.2节Nginx配置中的location /api/部分。

五、SSL证书配置(HTTPS)

5.1 申请免费SSL证书

使用Certbot申请Let’s Encrypt免费证书:

# 安装Certbot
sudo apt-get install certbot python3-certbot-nginx

# 申请证书
sudo certbot --nginx -d your-domain.com

# 自动续期
sudo certbot renew --dry-run

5.2 Nginx HTTPS配置

server {
    listen 443 ssl http2;
    server_name your-domain.com;
    
    ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    
    # 其他配置同HTTP
    location / {
        root /www/wwwroot/frontend/dist;
        index index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    
    location /api/ {
        proxy_pass http://127.0.0.1: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_set_header X-Forwarded-Proto $scheme;
    }
}

# HTTP重定向到HTTPS
server {
    listen 80;
    server_name your-domain.com;
    return 301 https://$server_name$request_uri;
}

六、性能优化配置

6.1 Nginx性能优化

# 开启Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;

# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

# 反向代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

location /api/ {
    proxy_cache my_cache;
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 404 1m;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    add_header X-Cache-Status $upstream_cache_status;
}

6.2 后端服务优化

JVM参数优化:

nohup java -server \
-Xms512m -Xmx1024m \
-XX:+UseG1GC \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/tmp/heapdump.hprof \
-jar your-project.jar > app.log 2>&1 &

SpringBoot配置优化:

server:
  tomcat:
    max-threads: 200
    min-spare-threads: 10
    accept-count: 100
    max-connections: 10000

七、监控与日志管理

7.1 日志配置

SpringBoot日志配置:

logging:
  level:
    com.yourpackage: DEBUG
  file:
    name: /var/log/your-project/application.log
    max-size: 10MB
    max-history: 30
  logback:
    rollingpolicy:
      max-file-size: 10MB
      total-size-cap: 1GB

Nginx日志配置:

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                   '$status $body_bytes_sent "$http_referer" '
                   '"$http_user_agent" "$http_x_forwarded_for"';
    
    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log;
}

7.2 监控配置

使用Spring Boot Actuator:

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
  endpoint:
    health:
      show-details: always

使用Prometheus监控:

management:
  endpoints:
    web:
      exposure:
        include: prometheus
  metrics:
    export:
      prometheus:
        enabled: true

八、常见问题与解决方案

8.1 前端页面刷新404

问题原因:​ Vue Router的history模式需要Nginx配置支持。

解决方案:

location / {
    root /www/wwwroot/frontend/dist;
    index index.html index.htm;
    try_files $uri $uri/ /index.html;
}

8.2 静态资源加载失败

问题原因:​ 静态资源路径配置错误或权限不足。

解决方案:

# 检查路径是否正确
ls -la /www/wwwroot/frontend/dist/

# 设置权限
chown -R www-data:www-data /www/wwwroot/frontend
chmod -R 755 /www/wwwroot/frontend

8.3 跨域问题

问题原因:​ 前后端域名或端口不一致。

解决方案:

  • 后端配置CORS(见4.1节)
  • Nginx配置代理(见3.2节)
  • 前端配置代理(开发环境)

8.4 数据库连接失败

问题原因:​ MySQL未启动或配置错误。

解决方案:

# 检查MySQL状态
systemctl status mysql

# 启动MySQL
systemctl start mysql

# 检查防火墙
firewall-cmd --list-all

# 检查MySQL用户权限
mysql -u root -p
SELECT Host, User FROM mysql.user;

8.5 端口被占用

问题原因:​ 其他服务占用了相同端口。

解决方案:

# 查看端口占用
netstat -tlnp | grep :8080

# 杀死占用进程
kill -9 进程ID

# 或者修改服务端口
server:
  port: 9090

九、总结

通过以上步骤,可以完成SpringBoot+Vue前后端分离项目在云服务器上的完整部署。关键要点包括:

  1. 环境准备:确保JDK、MySQL、Nginx等基础环境安装正确
  2. 后端部署:打包JAR文件,配置数据库连接,使用systemd管理服务
  3. 前端部署:打包dist目录,配置Nginx代理和静态资源服务
  4. 跨域处理:通过后端CORS配置或Nginx代理解决跨域问题
  5. HTTPS配置:使用Certbot申请免费SSL证书,配置HTTPS访问
  6. 性能优化:配置Gzip压缩、静态资源缓存、JVM参数优化
  7. 监控日志:配置日志输出和监控端点

整个部署过程需要严格按照步骤执行,确保每个环节的配置正确。部署完成后,建议进行全面的功能测试和性能测试,确保系统稳定运行。

版权声明:本文为JienDa博主的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
若内容若侵犯到您的权益,请发送邮件至:platform_service@jienda.com我们将第一时间处理!
所有资源仅限于参考和学习,版权归JienDa作者所有,更多请访问JienDa首页。

给TA赞助
共{{data.count}}人
人已赞助
阅读

前端小白的 Webpack 扫盲指南

2025-12-10 2:02:21

阅读

企业实现知识管理的难点和解决方法

2025-12-10 8:24:15

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索