You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从外部psql客户端访问Testcontainers中的PostgreSQL数据库

问题原因与解决方法

核心问题

Testcontainers 默认会随机分配主机端口映射容器内部的5432端口,避免本地端口冲突。你直接用默认的5432端口连接,自然会被拒绝。

解决步骤

1. 获取容器实际映射的主机端口

在断点触发时,通过以下方式获取映射端口:

  • 调试模式下,查看postgres对象的getMappedPort(5432)返回值;
  • 或者临时修改测试代码,在断点前打印端口:
    @Test
    void exampleTest() {
        // 打印映射到本地的端口
        System.out.println("PostgreSQL 本地映射端口: " + postgres.getMappedPort(5432));
        System.out.println("Hello world");
    }
    

2. 使用正确端口连接psql

将获取到的端口替换到命令中,比如实际端口是54321,执行:

psql -h localhost -U test -d test -p 54321

可选:固定端口(不推荐)

如果需要固定使用5432端口,修改容器初始化代码(注意本地5432端口需未被占用):

static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:14-alpine")
        .withInitScript("schema.sql")
        // 固定端口映射
        .withCreateContainerCmdModifier(cmd -> 
            cmd.withHostConfig(new HostConfig().withPortBindings(
                new PortBinding(Ports.Binding.bindPort(5432), new ExposedPort(5432))
            ))
        );

此时即可直接用psql -h localhost -U test -d test连接。


内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 23:32:33