java - 无法连接到测试容器 Postgres 实例

标签 java spring postgresql spring-boot testcontainers

我已经使用测试容器创建了一个 Postgres 实例。容器已启动,但我无法访问它。

我尝试使用 DBeaver 连接容器化数据库。 在 Eclipse 控制台中,一切似乎都很好:

01:29:34.662 [main] DEBUG com.github.dockerjava.core.command.AbstrDockerCmd - Cmd: com.github.dockerjava.core.command.CreateContainerCmdImpl@73386d72[name=,hostName=,domainName=,user=,attachStdin=,attachStdout=,attachStderr=,portSpecs=,tty=,stdinOpen=,stdInOnce=,env={POSTGRES_USER=test,POSTGRES_PASSWORD=test,POSTGRES_DB=ASIGDB_TEST}

这是我的代码:

public class CustomPostgresContainer extends PostgreSQLContainer<CustomPostgresContainer>{
    private static final String IMAGE_VERSION = "postgres:9.6";
    private static CustomPostgresContainer customPostgresContainer;
    private static final int EXPOSED_PORT = 5555;
    private static final String DB_NAME = "ASIGDB_TEST";
    private static final String DB_USER= "test";
    private static final String DB_PASSWORD= "test";


    public CustomPostgresContainer() {
        super(IMAGE_VERSION);
    }

    public static CustomPostgresContainer getCustomPostgresContainerInstance() {
        if(customPostgresContainer == null) {
            return extracted().withExposedPorts(EXPOSED_PORT)
                                                .withDatabaseName(DB_NAME)
                                                .withUsername(DB_USER)
                                                .withPassword(DB_PASSWORD);
        }

        return customPostgresContainer;
    }

    private static CustomPostgresContainer extracted() {
        return new CustomPostgresContainer();
    }

    @Override
    public void start() {
        super.start();
    }

    @Override
    public void stop() {
        //do nothing, JVM handles shut down
    }
}

我得到:

Connection to localhost:5555 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

有人知道这是怎么回事吗?

最佳答案

根据 this link , withExposedPorts() --> 这个暴露的端口号是从容器的角度来看的。
从主机的角度来看,Testcontainers 实际上在一个随机的空闲端口上公开了它。这是设计使然,以避免本地运行的软件或并行测试运行之间可能出现的端口冲突。
因为有这层间接,所以需要在运行时向Testcontainers询问实际映射的端口。这可以使用 getMappedPort 方法来完成,该方法将原始(容器)端口作为参数:

Integer firstMappedPort = container.getMappedPort(yourExposedPort);<br/>

尝试用 DBeaver 连接到最先出现的端口。

Screenshot with ports

关于java - 无法连接到测试容器 Postgres 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58150827/

相关文章:

spring - JdbcTemplate - 替换问号

linux - 如何提高 Postgresql 'truncate' 性能?

php - psql - 根角色不存在

java - 如何使用 jpa 将数组参数传递给 postgresql 函数?

java - 在spring mvc框架中使用Spring加载

spring - Spring SEO的建议

java - 使用JLabel添加图片的问题

使用 Jackson PTH 和 Spring Data MongoDB DBRef 的 Java 到 JSON 序列化生成额外的目标属性

java - 为什么接口(interface)是静态的?

java 7 功能无法在 java 版本 "1.7.0_51"的 ubuntu 上运行