【问题标题】:Can't connect to a testcontainer Postgres instance无法连接到测试容器 Postgres 实例
【发布时间】:2020-01-28 17:47:06
【问题描述】:

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

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

01:29:34.662 [main] 调试 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
    }
}

我明白了:

与 localhost:5555 的连接被拒绝。检查主机名和端口是否正确,以及 postmaster 是否接受 TCP/IP 连接。

有人知道怎么回事吗?

【问题讨论】:

    标签: java spring postgresql spring-boot testcontainers


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢维塔利。我确实误解了暴露端口的观点。基本上,由 testcontainers 启动的对 docker 入口点(在该随机端口上公开)的任何请求都会转发到在容器内运行的默认 postgres 实例(5432)和我添加的公开端口(5555)。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 2019-08-11
    • 2020-10-09
    • 2019-05-05
    • 1970-01-01
    相关资源
    最近更新 更多