You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker部署SpringBoot+NodeJS+MySQL时数据库连接失败求助

解决Docker部署下前后端交互的跨域及数据库连接问题

一、补全SpringBoot后端CORS配置

仅配置allowHeaders无法覆盖完整的跨域需求,需确保以下关键配置项齐全:

  • 允许的请求源:指定前端实际访问地址(如http://localhost:3000),生产环境避免用*
  • 允许的请求方法:覆盖POST、GET、OPTIONS等前端用到的所有请求类型
  • 允许携带凭证:若前端需传递Cookie或认证信息,必须设为true
  • 暴露响应头:前端需要读取的自定义响应头需在此声明

示例完整配置(可写在Application.java或单独的CORS配置类中):

@Bean
public CorsFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    // 替换为你的前端实际地址
    config.addAllowedOrigin("http://localhost:3000");
    config.addAllowedMethod("*");
    config.addAllowedHeader("*");
    config.setAllowCredentials(true);
    config.addExposedHeader("Authorization");

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    // 对所有接口生效
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

二、修正Docker网络与请求地址

  1. 容器内服务调用规则:前端请求后端时,需用docker-compose中后端的服务名而非localhost。比如后端服务名为backend,前端请求地址应为http://backend:8080/api/xxx——因为浏览器端的localhost指向宿主机,和容器内后端地址不匹配会触发跨域。
  2. 容器启动顺序:确保MySQL完全启动后再启动后端,可通过docker-compose的健康检查实现:
services:
  mysql:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: your_password
      MYSQL_DATABASE: your_db_name
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      timeout: 20s
      retries: 10
  backend:
    build: ./backend
    depends_on:
      mysql:
        condition: service_healthy

三、处理OPTIONS预检请求

浏览器发送非简单请求(如带自定义头的POST)前会先发送OPTIONS预检,需确保后端不拦截该请求:

  • 若使用Spring Security,需添加放行规则:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        // 其他安全配置...
}

四、验证数据库连接配置

后端配置文件中,数据库URL需使用MySQL服务名而非localhost,示例:

spring:
  datasource:
    url: jdbc:mysql://mysql:3306/your_db_name?useSSL=false&serverTimezone=UTC
    username: root
    password: your_password

内容的提问来源于stack exchange,提问作者Chels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:06:23