Ubuntu TestContainers 无法连接到 Postgis:9.5

Ubuntu TestContainers unable to connect to Postgis:9.5

我准备了 TestContainers(版本 1.12.2)模块的以下定义,以在我们的应用程序中测试 liquibase 模式。尝试执行时,我收到 Connection Refused 错误,就像它不存在一样,但是在测试的 运行 期间,我检查了容器及其启动:

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 测试 运行 期间的结果:

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

错误:

org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

testcontainers中暴露一个端口的时候,其实用的不是同一个端口,而是另一个。 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.

您需要向容器询问映射端口:

Integer actualPostgresPort = container.getMappedPort(5432);

如果分析 docker ps 的输出,您会发现端口 5432 没有被暴露,而是 32784。