java - Ubuntu TestContainers 无法连接到 Postgis :9. 5

标签 java docker ubuntu testcontainers

我有以下 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。

关于java - Ubuntu TestContainers 无法连接到 Postgis :9. 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60317594/

相关文章:

docker - 从主机连接到在 Docker 容器中运行的 Redis

docker - OSX上的Docker初始化:拨号错误是否正常?

amazon-web-services - 使用 Kubernetes 部署 - Master 和 Nodes 在同一台机器上的可行性

java - 让我的 java swing 动画在 Linux 中更流畅

java - 如何在 IntelliJ 控制台中隐藏或忽略 System.err 输出

java - Gradle & Groovy - 错误 : Could not find or load main class

sql-server - 使用 EF Core、Docker 和系统分配标识从 Web 应用程序访问 Azure SQL

javascript - ubuntu 12.04上的nodejs vs node

java - 从java中的数组中找出n个缺失元素

java - 如何解决 Java 8 中的这个 'Lambdas should be replaced with method references' 声纳问题?