Search code examples
javapostgresqltestcontainers

How to access db in testcontainers from external client


I have a standard SpringBoot JPA project with PostgreSQL database. For integration tests I use testcontainers. Everything works fine but if some test fails I'd like run it in debug mode with an appropriate breakpoint and investigate what is the database state - what tables, records in tables and so on it has preferably with psql client working from terminal. My base test looks like

public class TestContainersExampleIT {

    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>(
            "postgres:14-alpine"
    );

    @BeforeAll
    static void beforeAll() {
        postgres.withInitScript("schema.sql");
        postgres.start();
    }

    @AfterAll
    static void afterAll() {
        postgres.stop();
    }

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        registry.add("datasource.kedr.postgres.jdbcUrl", postgres::getJdbcUrl);
        registry.add("datasource.kedr.postgres.username", postgres::getUsername);
        registry.add("datasource.kedr.postgres.password", postgres::getPassword);
    }

    @Test
    void exampleTest() {
        System.out.println("Hello world");
    }

}

The question is how can I connect to this database with psql client ?

I put break point at System.out.println() and run test in debug mode. It stops at break point and database seems running. At this moment I try to connect to it as


psql -h localhost -U test -d test

and got

psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?

What I do wrong? Please help. Thank you in advance


Solution

  • Connection refused suggests maybe problem with the user / PW. Perhaps print out the URL / username / PW when spinning it up and compare.

    Another possibility is that the testcontainer doesn't have an exposed port linked to your computer's port.