Spring Boot中Testcontainers MySQLContainer无法访问问题求助(8.3/8.4版本)
解决Testcontainers连接MySQL 8.3/8.4镜像超时失败的问题
问题根源
MySQL 8.3.0和8.4.0版本镜像默认启用了caching_sha2_password认证插件,而Testcontainers的默认连接配置(以及Spring Boot自动注入的JDBC参数)未适配该插件的要求,同时容器启动后数据库就绪的判断逻辑不匹配新版本的日志输出,导致连接超时、容器退出。
解决方案
1. 切换兼容的认证插件
启动MySQL容器时显式指定使用mysql_native_password插件,这是Testcontainers默认支持的认证方式,无需额外JDBC参数配置:
@Testcontainers @SpringBootTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) public class AnglerMapperTest { @Container @ServiceConnection static MySQLContainer<?> mySQLContainer = new MySQLContainer<>(DockerImageName.parse("mysql:8.4.0")) .withStartupTimeout(Duration.ofSeconds(180)) // 关键配置:指定兼容的认证插件 .withCommand("--default-authentication-plugin=mysql_native_password") // 等待数据库完全就绪的日志标记(比端口等待更可靠) .waitingFor(Wait.forLogMessage(".*ready for connections.*", 1)); @Autowired AnglerMapper anglerMapper; @Test void connection_established() { assertThat(mySQLContainer.isCreated()).isTrue(); assertThat(mySQLContainer.isRunning()).isTrue(); } }
2. 确保Testcontainers版本兼容
升级testcontainers-mysql依赖到1.19.8或更高版本,这些版本已经适配了MySQL 8.3+的启动逻辑:
<!-- Maven依赖示例 --> <dependency> <groupId>org.testcontainers</groupId> <artifactId>mysql</artifactId> <version>1.19.8</version> <scope>test</scope> </dependency>
3. 可选:调整Docker资源配置
如果Docker环境资源不足(CPU/内存),MySQL容器可能启动缓慢导致超时。可以在Docker Desktop的设置中增加分配的CPU核心数(建议2核以上)和内存(建议4GB以上)。
替代方案(不修改认证插件)
如果必须使用caching_sha2_password,需要在JDBC URL中添加适配参数:
// 自定义JDBC URL参数 static MySQLContainer<?> mySQLContainer = new MySQLContainer<>(DockerImageName.parse("mysql:8.4.0")) .withStartupTimeout(Duration.ofSeconds(180)) .withJdbcUrlParam("allowPublicKeyRetrieval", "true") .withJdbcUrlParam("useSSL", "false");
这种方式需要确保JDBC驱动版本(mysql-connector-java 8.0+)支持这些参数。
内容的提问来源于stack exchange,提问作者Nemanja Novakovic
相关产品推荐
相关产品推荐

