【问题标题】:How can I set the port for Postgresql when using Testcontainers?使用 Testcontainers 时如何设置 Postgresql 的端口?
【发布时间】:2021-11-06 23:25:06
【问题描述】:

有时我需要为 Postgresql 安装一个端口,我在容器中运行该端口进行测试。但是Test容器的开发者命令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);
    }

}

【问题讨论】:

    标签: postgresql spring-boot java-11 testcontainers


    【解决方案1】:

    添加与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();
    }
    

    【讨论】:

    • 我收到一个错误 - 如果我设置端口 5437 或其他端口(例如 32700):java.lang.IllegalArgumentException: 请求的端口 (5432) 未映射。如果我设置端口 5432 ,会出现一条错误消息: (48165926feea259777b85edc2a6e9567516841a4121ae924a6836e46d816ffb0): Bind for 0.0.0.0:5432 failed: port is already assigned"}
    • 我已经更新了答案。对于 postgresql,容器端口应该是 5432。如果更改本地端口显示错误消息“端口已分配”,请检查您是否正在同一端口上运行另一个容器。可以通过 docker ps 查看,通过 docker stop [CONTAINER ID] 停止。
    • 就是这样,我不想被绑定到端口 5432 。我想自己分配端口。我认为目前需要的东西
    猜你喜欢
    • 2021-09-26
    • 2019-09-22
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多