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

Testcontainers MariaDB容器添加初始化脚本后遇权限拒绝问题

解决Testcontainers MariaDB容器初始化脚本导致的权限拒绝问题

问题描述

使用Testcontainers创建MariaDB容器用于JPA测试,添加初始化脚本后出现权限拒绝错误:

Caused by: java.sql.SQLSyntaxErrorException: Access denied for user 'test'@'%' to database 'test_schema'

容器代码:

private static final String CONTAINER_IMAGE_NAME = TestcontainersConfiguration.getInstance()
        .getEnvVarOrProperty("mariadb.container.image", "mariadb:10.2.18");

private static final MariaDBContainer<?> PRIMARY_MARIADB_SQL_CONTAINER = new MariaDBContainer<>(
    DockerImageName.parse(CONTAINER_IMAGE_NAME).asCompatibleSubstituteFor("mariadb")
)
    .withDatabaseName("db")
    .withUsername("test")
    .withPassword("password")
    .withPrivilegedMode(true)
    .withInitScript("mariadb/init.sql");

初始化脚本init.sql:

CREATE SCHEMA IF NOT EXISTS test_schema;

GRANT ALL PRIVILEGES ON test_schema.* TO 'test'@'%' WITH GRANT OPTION;

FLUSH PRIVILEGES;

问题原因

Testcontainers的withInitScript方法会使用你指定的test用户连接数据库并执行脚本,但默认情况下:

  • test用户仅拥有withDatabaseName指定的db数据库的全部权限,对新创建的test_schema无访问权限
  • test用户没有GRANT权限,无法执行授权语句,导致脚本中的授权操作失败,最终test用户无法访问test_schema

解决方案

将初始化脚本复制到MariaDB容器的/docker-entrypoint-initdb.d/目录下,该目录下的脚本会在容器启动时以root用户自动执行,root拥有足够权限完成授权操作。

修改容器代码如下:

private static final String CONTAINER_IMAGE_NAME = TestcontainersConfiguration.getInstance()
        .getEnvVarOrProperty("mariadb.container.image", "mariadb:10.2.18");

private static final MariaDBContainer<?> PRIMARY_MARIADB_SQL_CONTAINER = new MariaDBContainer<>(
    DockerImageName.parse(CONTAINER_IMAGE_NAME).asCompatibleSubstituteFor("mariadb")
)
    .withDatabaseName("db")
    .withUsername("test")
    .withPassword("password")
    .withPrivilegedMode(true)
    // 替换withInitScript为复制文件到容器初始化目录
    .withCopyFileToContainer(MountableFile.forClasspathResource("mariadb/init.sql"), "/docker-entrypoint-initdb.d/init.sql");

保持原init.sql内容不变即可,root用户执行脚本后,test用户会被正确授予test_schema的全部权限。

另外需确保你的JPA数据源配置指向test_schema:

spring.datasource.url=jdbc:mariadb://${testcontainers.mariadb.host}:${testcontainers.mariadb.port}/test_schema
spring.datasource.username=test
spring.datasource.password=password

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:40:35