让 pgAdmin 和 PostgreSQL 运行在同一个 Docker 网络中。

张开发
2026/4/9 1:53:32 15 分钟阅读

分享文章

让 pgAdmin 和 PostgreSQL 运行在同一个 Docker 网络中。
明白了您希望用 pgAdmin 来管理运行在 Docker 容器里的 PostgreSQL 数据库。最可靠且易于管理的方式是让 pgAdmin 和 PostgreSQL 运行在同一个 Docker 网络中。下面给您一个最简洁的Docker Compose 方案您只需要复制保存、启动就能通过浏览器访问 pgAdmin 并连接数据库。✅ 推荐方案使用 Docker Compose1. 创建docker-compose.yml文件version:3.8services:postgres:image:postgres:latestcontainer_name:my_postgresrestart:alwaysenvironment:POSTGRES_USER:admin# 数据库用户名POSTGRES_PASSWORD:secret123# 数据库密码POSTGRES_DB:mydb# 默认数据库名ports:-5432:5432volumes:-postgres_data:/var/lib/postgresql/datanetworks:-pg_networkpgadmin:image:dpage/pgadmin4:latestcontainer_name:my_pgadminrestart:alwaysenvironment:PGADMIN_DEFAULT_EMAIL:adminexample.com# pgAdmin 登录邮箱PGADMIN_DEFAULT_PASSWORD:pgadmin123# pgAdmin 登录密码ports:-5050:80depends_on:-postgresnetworks:-pg_networknetworks:pg_network:driver:bridgevolumes:postgres_data:2. 启动服务在docker-compose.yml所在目录执行docker-composeup-d3. 登录 pgAdmin 并添加数据库服务器打开浏览器访问http://localhost:5050登录邮箱adminexample.com密码pgadmin123点击Add New ServerName任意填写如我的PostgreSQLConnection页签Host name/address填写postgres这是 Compose 中的服务名会被自动解析为 PostgreSQL 容器的 IPPort5432Maintenance databasemydbUsernameadminPasswordsecret123点击Save即可完成连接。⚠️ 关键点说明为什么主机地址填postgres而不是localhost因为两个容器在同一个自定义网络pg_network中可以直接用服务名postgres互相访问。localhost在 pgAdmin 容器里指向它自己所以填localhost会连接失败。如果想把 pgAdmin 安装在本机非容器连接时主机地址填localhost但必须确保 PostgreSQL 容器将端口映射到宿主机上面已经做了ports: - 5432:5432。 测试连接是否正常进入 PostgreSQL 容器创建一个测试表然后通过 pgAdmin 查看dockerexec-itmy_postgres psql-Uadmin-dmydb在 psql 中执行CREATETABLEtest(idint);\d刷新 pgAdmin 左侧树就能看到新建的表。如果您在操作中遇到具体错误比如容器无法启动、连接超时等请把错误信息发给我我会帮您分析解决。

更多文章