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

如何查看PostgreSQLContainer容器内的数据库插入记录

问题描述

我用以下Java代码创建了PostgreSQLContainer实例:

public static PostgreSQLContainer postgres = (PostgreSQLContainer) new PostgreSQLContainer<>("postgres")
        .withCreateContainerCmdModifier(cmd -> cmd.withName("postgres-sql"))
        .withNetworkAliases("postgres")
        .withStartupTimeoutSeconds(240)
        .withConnectTimeoutSeconds(240)
        .withNetwork(componentTestNetwork)
        .withFileSystemBind(pathToFile + "/postgres/", "/postgres", BindMode.READ_WRITE)
        .withExposedPorts(5432)
        .withStartupAttempts(10)
        .withInitScript("postgres/create_table.sql")
        .waitingFor(Wait.forHealthcheck());

对应的初始化脚本create_table.sql内容如下:

CREATE SCHEMA IF NOT EXISTS techwriting;

CREATE TABLE IF NOT EXISTS techwriting.book(
id int NOT NULL,
name varchar(10) NOT NULL,
description varchar(10) NOT NULL,
CONSTRAINT book_pkey PRIMARY KEY (id));


INSERT INTO techwriting.book (id,name,description) VALUES
(1,'premchand','classical');
INSERT INTO techwriting.book (id,name,description) VALUES
(2,'nirala','horror');
INSERT INTO techwriting.book (id,name,description) VALUES
(3,'premchand','horror');
INSERT INTO techwriting.book (id,name,description) VALUES
(4,'premchand','xyz');

现在Docker Desktop已经启动,PostgreSQL容器也创建成功了,但我找不到脚本里插入的记录——只能看到容器的卷,里面都是PostgreSQL相关的文件,不知道该怎么找到那些插入的数据。

解决办法

1. 直接进容器查数据(最靠谱的方式)

打开终端,执行命令进入你的PostgreSQL容器:

docker exec -it postgres-sql psql -U test test

(注:Testcontainers默认的PostgreSQL用户名和数据库名都是test,如果你改了配置,就换成你自己的)

进入psql命令行后,先切换到techwriting schema:

SET search_path TO techwriting;

然后查询book表:

SELECT * FROM book;

如果初始化脚本执行正常,这里就能看到那4条插入的记录。

2. 用本地工具连接容器查

先看看容器把5432端口映射到本地哪个端口了:

docker port postgres-sql 5432

输出会是类似0.0.0.0:54321或者127.0.0.1:54321的格式,后面的数字就是本地端口。

然后用pgAdmin、DBeaver这类PostgreSQL客户端连接,参数填:

  • 主机:localhost
  • 端口:上面查到的本地端口
  • 数据库:test
  • 用户名:test
  • 密码:test(Testcontainers默认密码)

连接上之后,切换到techwriting schema,直接查book表就能看到数据。

3. 先确认初始化脚本到底执行了没

如果上面两种方式都没查到数据,先看看脚本是不是没跑:

  • 查看容器日志,搜create_table.sql相关内容:
    docker logs postgres-sql
    
    看看有没有执行成功的日志,或者有没有报错(比如字段长度不够、语法写错了之类的)。
  • 另外,Testcontainers的withInitScript要求脚本路径是相对于classpath的,你得确认postgres/create_table.sql是不是真的在项目的classpath下面,路径有没有写错。

4. 关于容器卷里的文件

你在Docker Desktop看到的卷是PostgreSQL默认的数据存储目录(一般是/var/lib/postgresql/data),但这里面的数据都是二进制格式的,没法直接打开看。如果要把数据导出来看,可以在终端执行:

docker exec postgres-sql pg_dump -U test -d test -n techwriting > book_data.sql

这条命令会把techwriting schema里的所有数据导出到本地的book_data.sql文件,打开这个文件就能看到插入的记录了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:59:54