在使用TestContainers时,如何为PostgreSQL设置端口? [英] How can I set the port for Postgresql when using Testcontainers?
本文介绍了在使用TestContainers时,如何为PostgreSQL设置端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有时我需要为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();
}
这篇关于在使用TestContainers时,如何为PostgreSQL设置端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文