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

Spring Boot+MySQL Docker容器启动失败:无法连接MySQL服务器求助

解决Spring Boot Docker容器无法连接MySQL的问题

问题描述

java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up

排查与解决步骤

1. 检查Docker网络配置

  • 确保Spring Boot容器和MySQL容器处于同一个Docker网络中。手动启动容器时,先创建网络:
    docker network create app-network
    
    启动两个容器时加入该网络:
    docker run --network=app-network --name mysql-container -e MYSQL_ROOT_PASSWORD=your-pw -d mysql:latest
    docker run --network=app-network --name spring-app -d your-spring-image
    
  • Spring Boot配置文件中,数据库地址不能用localhost,需改用MySQL容器的名称(如mysql-container)作为主机地址:
    spring.datasource.url=jdbc:mysql://mysql-container:3306/your-db?useSSL=false&serverTimezone=UTC
    

2. 等待MySQL容器初始化完成

  • Spring Boot启动速度快于MySQL初始化时,会导致连接失败。可通过以下方式处理:
    • 在Spring Boot配置中增加连接超时与重试参数:
      spring.datasource.hikari.connection-timeout=30000
      spring.datasource.hikari.max-lifetime=1800000
      spring.datasource.validation-query=SELECT 1
      spring.datasource.test-on-borrow=true
      
    • 在Dockerfile中添加wait-for-it脚本,启动前等待MySQL端口开放:
      COPY wait-for-it.sh /wait-for-it.sh
      RUN chmod +x /wait-for-it.sh
      CMD ["/wait-for-it.sh", "mysql-container:3306", "--", "java", "-jar", "your-app.jar"]
      

3. 验证MySQL容器配置

  • 启动MySQL容器时,需设置允许外部连接的环境变量,确保Spring Boot容器能访问:
    docker run --network=app-network --name mysql-container -e MYSQL_ROOT_HOST=% -e MYSQL_ROOT_PASSWORD=your-pw -e MYSQL_DATABASE=your-db -d mysql:latest
    
  • 确认配置文件中的数据库用户名、密码与MySQL容器设置一致:
    spring.datasource.username=root
    spring.datasource.password=your-pw
    

4. 检查驱动与MySQL版本兼容性

  • MySQL 8.x版本需使用对应版本的驱动,配置文件中指定正确的驱动类:
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    
  • 确保pom.xml(或build.gradle)中的驱动版本匹配:
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.33</version>
    </dependency>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:31:17