0

I have the following definition of TestContainers (version 1.12.2) module prepared to test liquibase schema in our app. When trying to execute I'm receiving Connection Refused error like it would not exist, however during run of the test I've checked containers and their up:

private static final String DB_URL = String.format("jdbc:postgresql://%s:%s/%s", "localhost", 5432, DB_NAME);

    @Rule
    public final GenericContainer<?> container = 
            new GenericContainer<>("mdillon/postgis:9.5")
                .withExposedPorts(5432)
                .withEnv("POSTGRES_USER", USER)
                .withEnv("POSTGRES_PASSWORD", PASSWORD)
                .withEnv("POSTGRES_DB", DB_NAME);

    @Test
    public void transactionSchemaWasUpdated() throws Exception {
        try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASSWORD)) {
            // GIVEN
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
            database.setDefaultSchemaName(SCHEMA);
            Liquibase liquibase = new Liquibase("install.xml", new ClassLoaderResourceAccessor(), database);
            liquibase.setChangeLogParameter("schemaName", SCHEMA);
            // WHEN
            liquibase.update("main");
            // THEN
            assertEquals(getAppVersion(), getDbVersion(connection));
        }
    }

Docker ls result during run of tests:

378e828e4149        mdillon/postgis:9.5                 "docker-entrypoint.s…"   7 seconds ago       Up 6 seconds        0.0.0.0:32784->5432/tcp   thirsty_stonebraker
6a270c963322        quay.io/testcontainers/ryuk:0.2.3   "/app"                   8 seconds ago       Up 7 seconds        0.0.0.0:32783->8080/tcp   testcontainers-ryuk-78a4fc8d-4fb9-41bf-995f-b31076b02465

Error:

org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
ashur
  • 4,177
  • 14
  • 53
  • 85

1 Answers1

2

When a port is exposed in testcontainers, it actually does not use the same port, but another one. According docs:

From the host's perspective Testcontainers actually exposes this on a random free port. This is by design, to avoid port collisions that may arise with locally running software or in between parallel test runs.

You need to ask the container for the mapped port:

Integer actualPostgresPort = container.getMappedPort(5432);

If you analyze the output of docker ps, you will see that port 5432 is not being exposed, but 32784 instead.

Héctor
  • 24,444
  • 35
  • 132
  • 243
  • It is kinda weird, because I switched from windows 10 to ubuntu two days ago and it worked on W10, no idea why it started to fail now, since I had almost the same mapping from `docker container ls`. – ashur Feb 20 '20 at 11:48
  • 1
    Edit. It is possible I had postgres installed on my Win10 Machine. This is the reason it worked. – ashur Mar 03 '20 at 08:36