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

Linux主机无法通过localhost连接Docker容器PostgreSQL的问题

PostgreSQL Docker容器连接失败解决办法

问题重现

启动容器命令:

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

尝试用DBeaver通过localhost:5432,用户名postgres、密码mysecretpassword连接时,报错:

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

核心原因与解决步骤

1. 确保端口正确映射到宿主机

你之前的启动命令未添加端口映射参数-p,容器的5432端口并未暴露给宿主机,这是连接失败的主要原因。正确的启动命令如下:

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres

参数说明:-p 宿主机端口:容器端口,这里将宿主机的5432端口和容器内的5432端口绑定。

如果容器已经启动,需先停止并删除旧容器,再重新启动:

docker stop some-postgres
docker rm some-postgres
# 执行正确的启动命令
docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres

2. 验证端口映射状态

执行docker ps查看容器信息,检查PORTS列是否显示类似0.0.0.0:5432->5432/tcp或:::5432->5432/tcp,这表示端口映射已生效。

也可以在宿主机上检查端口监听状态:

  • Linux/macOS:
    netstat -an | grep 5432
    
  • Windows:
    netstat -ano | findstr :5432
    

若输出中包含LISTENING状态,说明宿主机端口已正常监听。

3. 确认PostgreSQL允许远程连接

Postgres官方镜像默认已配置允许远程连接,可进入容器验证:

docker exec -it some-postgres bash
# 检查监听地址
cat /var/lib/postgresql/data/postgresql.conf | grep listen_addresses

应输出listen_addresses = '*',表示允许所有IP访问。

再检查访问控制规则:

cat /var/lib/postgresql/data/pg_hba.conf | grep 0.0.0.0

应存在一行host all all 0.0.0.0/0 scram-sha-256,允许任意IP通过密码认证连接。

4. 连接参数确认

连接DBeaver时使用以下参数:

  • 主机:localhost(宿主机直接连接)或host.docker.internal(Docker Desktop环境下替代localhost)
  • 端口:5432(与映射的宿主机端口一致)
  • 用户名:postgres
  • 密码:mysecretpassword

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 11:47:35