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