skyho
skyho

Reputation: 1903

How can I set the port for Postgresql when using Testcontainers?

Sometimes I need to install a port for Postgresql, which I run for tests in a container. But the Test container the developer command ofTestcontainers removed this feature. But somewhere there is a workaround solution, through the settings, but I can't find it. Who has any ideas or information on how to do this ?

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);
    }

}

Upvotes: 11

Views: 13438

Answers (1)

Ashutosh
Ashutosh

Reputation: 2957

Add port binding with 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();
}

Upvotes: 12

Related Questions