使用 Testcontainers 时如何设置 Postgresql 的端口?

sky*_*yho 10 postgresql spring-boot testcontainers java-11

有时我需要为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);
    }

}

Run Code Online (Sandbox Code Playgroud)

Ash*_*osh 10

添加端口绑定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();
}
Run Code Online (Sandbox Code Playgroud)