问题描述
有时我需要为PostgreSQL安装一个端口,我在容器中运行该端口进行测试。但测试容器,即开发人员对TestContainers的命令,删除了这一功能。但在某个地方,通过设置,有一个解决方案,但我找不到它。谁有关于如何做到这一点的想法或信息?
public class ContainerConfig {
private static final PostgreSQLContainer postgresSQLContainer;
static {
DockerImageName postgres = DockerImageName.parse("postgres:13.1");
postgresSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer(postgres)
.withDatabaseName("test")
.withUsername("root")
.withPassword("root")
.withReuse(true);
postgresSQLContainer.start();
}
@SuppressWarnings("rawtypes")
private static PostgreSQLContainer getPostgresSQLContainer() {
return postgresSQLContainer;
}
@SuppressWarnings("unused")
@DynamicPropertySource
public static void registerPgProperties(DynamicPropertyRegistry propertyRegistry) {
propertyRegistry.add("integration-tests-db", getPostgresSQLContainer()::getDatabaseName);
propertyRegistry.add("spring.datasource.username", getPostgresSQLContainer()::getUsername);
propertyRegistry.add("spring.datasource.password", getPostgresSQLContainer()::getPassword);
propertyRegistry.add("spring.datasource.url", getPostgresSQLContainer()::getJdbcUrl);
}
}
推荐答案
添加withCreateContainerCmdModifier
端口绑定。
static {
int containerPort = 5432 ;
int localPort = 5432 ;
DockerImageName postgres = DockerImageName.parse("postgres:13.1");
postgreDBContainer = new PostgreSQLContainer<>(postgres)
.withDatabaseName("test")
.withUsername("root")
.withPassword("root")
.withReuse(true)
.withExposedPorts(containerPort)
.withCreateContainerCmdModifier(cmd -> cmd.withHostConfig(
new HostConfig().withPortBindings(new PortBinding(Ports.Binding.bindPort(localPort), new ExposedPort(containerPort)))
));
postgreDBContainer.start();
}