Skip to content

数据库连接失败

错误信息

                错误: 连接 ECONNREFUSED <db-host>:5432
              

快速摘要

application cannot establish 连接到 数据库, 通常因为数据库是 下, unreachable, or credentials 是错误.

为什么发生

  • 数据库服务器是 不运行 or 有 crashed

  • Network issues prevent application 从 reaching 数据库

  • 数据库 credentials (用户名, 密码) 是不正确

  • 数据库连接 pool 是 exhausted — 也许多连接

最小示例

✗ 错误代码
# App cannot connect to database
DATABASE_URL=postgres://user:pass@db:5432/mydb
# Error: ECONNREFUSED — db is down
✓ 修复代码
# Check and restart database
kubectl get pods -l app=database
kubectl rollout restart deployment/database
# Wait for DB to be ready, then restart app
kubectl rollout restart deployment/app

数据库是 下. fix restarts 数据库 and 然后 application.

如何诊断

  • 检查如果数据库是 运行: kubectl 获取 pods -l app=数据库

  • 测试 connectivity: kubectl exec <app-pod> -- nc -zv <db-host> <db-port>

  • 验证数据库 credentials in Secret or 环境变量

  • 检查数据库连接限制 and current 连接

如何修复

  • 开始 or 重启数据库如果它 是下

  • Fix network connectivity or firewall 规则之间 app and 数据库

  • 正确数据库 credentials in Secret/ConfigMap

  • Increase 数据库最大值连接 or fix 连接 leaks in app

如何预防

  • Use 连接 pooling 使用 appropriate pool 大小

  • Monitor 数据库 health and 连接数量

  • Use init 容器到 wait for 数据库之前开始 app

相关资源

相关术语

← 返回语言