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

Flyway通过Docker连接PostgreSQL失败问题求助

Docker环境下Flyway连接PostgreSQL被拒绝问题解决

问题回顾

第一阶段:数据库类型无法识别

执行以下Flyway命令时出现错误:

$ docker run --rm -v /var/lib/jenkins/workspace/flyway@2/jenkins_flyway/sql:/flyway/sql -v /var/lib/jenkins/workspace/flyway@2/jenkins_flyway/conf:/flyway/conf flyway/flyway:10.13.0 -user=postgres -password=postgres migrate

错误输出:

WARNING: Storing migrations in 'sql' is not recommended and default scanning of this location may be deprecated in a future release
ERROR: No database found to handle "jdbc:postgresql://localhost:5432/mydb"

原因:Flyway配置文件中属性值使用了引号(比如flyway.url="jdbc:postgresql://localhost:5432/mydb"),去掉引号即可解决该错误。

第二阶段:连接被拒绝

修正配置后执行命令:

docker run --rm -v /var/lib/jenkins/workspace/flyway/jenkins_flyway/sql:/flyway/sql -v /var/lib/jenkins/workspace/flyway/jenkins_flyway/conf:/flyway/conf flyway/flyway:8.5.1 migrate

错误输出:

ERROR: Unable to obtain connection from database (jdbc:postgresql://localhost:5432/flyway) for user 'postgres': Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

SQL State : 08001
Error Code : 0
Message : Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

Caused by: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
Caused by: java.net.ConnectException: Connection refused (Connection refused)

核心原因:Docker容器内的localhost指向容器自身,而非宿主机上的PostgreSQL服务,导致连接失败。

解决方案

1. 使用宿主机Docker网桥IP替代localhost

  • 查看宿主机Docker网桥的IP(Linux系统执行ip addr show docker0,通常为172.17.0.1)
  • 修改Flyway配置中的JDBC URL为jdbc:postgresql://172.17.0.1:5432/flyway,重新执行命令

2. 使用Docker host网络模式

运行Flyway容器时添加--network host参数,让容器共享宿主机网络栈,此时localhost将指向宿主机:

docker run --rm --network host -v /var/lib/jenkins/workspace/flyway/jenkins_flyway/sql:/flyway/sql -v /var/lib/jenkins/workspace/flyway/jenkins_flyway/conf:/flyway/conf flyway/flyway:8.5.1 migrate

3. 若PostgreSQL为Docker容器,使用容器名作为主机名

  • 确保PostgreSQL容器与Flyway容器处于同一Docker网络(若未创建网络,执行docker network create flyway-net,启动PostgreSQL时添加--network flyway-net)
  • 修改JDBC URL为jdbc:postgresql://postgres-container:5432/flyway(替换postgres-container为你的PostgreSQL容器名称)

额外检查项

  • 确认PostgreSQL配置文件postgresql.conf中listen_addresses = '*',允许所有IP访问
  • 修改pg_hba.conf添加规则允许Docker网络连接:host all all 172.17.0.0/16 md5
  • 确认宿主机防火墙未拦截5432端口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:55:16