解决 Kong 报错 failed to connect to database postgres 不可达修复
排查 Kong Gateway 启动失败抛出 [postgres] failed to connect to database,分析 PG 连接池、密码认证与 SSL 模式。
问题现象
Kong 网关启动自检失败退出:
[error] 1#0: init_by_lua error: /usr/local/share/lua/5.1/kong/cmd/start.lua:64: [postgres] failed to connect to database: connection refused
触发根因
- PostgreSQL 服务尚未就绪:Docker Compose 编排中 Kong 启动快于数据库容器;
- PostgreSQL 宿主机的
pg_hba.conf拒绝了来自容器子网的密码认证; - 环境变量
KONG_PG_HOST或KONG_PG_PASSWORD配置错误。
解决步骤
使用 wait-for-it 脚本控制启动时序
在容器启动命令中增加数据库连通性轮询:
sh -c "/wait-for-it.sh postgres:5432 -- kong migrations up && kong start"
核实 PostgreSQL 监听与访问白名单
在 postgresql.conf 中确认 listen_addresses = '*',并在 pg_hba.conf 中允许子网:
hba: host all all 172.16.0.0/12 scram-sha-256
验证确认
执行配置验证与 Kong 启动:
kong start
输出 Kong started,控制平面顺利就绪。


