postgresql - 无法从另一个容器连接到 Postgres 容器
问题描述
这个问题已经在这里、这里和这里被问过很多次了,但是这些解决方案对我不起作用。
我用这个docker-compose.yml
文件创建了一个 Postgres 和一个 AppServer 容器
version: "3.7"
services:
db:
image: postgres:alpine
container_name: db
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: mydb
POSTGRES_INITDB_ARGS: '-A md5'
volumes:
- ./pgdata:/var/lib/postgressql/data
ports:
- "5432:5432"
api:
build: api
container_name: api
volumes:
- ./database/migrations:/migrations
ports:
- "8080:8080"
links:
- db
depends_on:
- db
运行此之后,我可以成功
docker exec -it db psql -U user mydb
我成功连接到 Postgres。我也可以成功登录到两个容器的终端
docker exec -it api bash
docker exec -it db bash
从 api 的 bash 内部我可以毫无问题地 ping db
但是,从我的 api 容器中,我无法建立到 Postgres 数据库的 JDBC 连接。
api | Flyway Community Edition 7.3.2 by Redgate
api | ERROR:
api | Unable to obtain connection from database (jdbc:postgresql://db:5432/mydb) for user 'user': Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
api | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
api | SQL State : 08001
api | Error Code : 0
api | Message : Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
api |
api | Caused by: org.postgresql.util.PSQLException: Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
api | Caused by: java.net.ConnectException: Connection refused (Connection refused)
当我可以通过 psql 连接时,为什么连接被拒绝?这是我的飞行路线
flyway.url=jdbc:postgresql://db:5432/mydb
flyway.user=user
flyway.password=password
flyway.locations=filesystem:/migrations
flyway migrate
编辑:: 所以如果我等待一段时间后再执行,docker exec -it api bash
一切正常。我认为上面发生的事情是我的flyway migrate
命令甚至在数据库准备好之前就在运行。
为什么会这样?因为我已经指定了依赖项,所以我的 API 容器应该仅在数据库完全启动时启动。但似乎并非如此。
解决方案
将数据库容器指定为依赖项并不能保证它会在您的其他服务/容器之前准备好。它只保证它将在您的其他服务之前启动。
解决此问题的一种方法是在启动期间无法连接到数据库时在 API 应用程序中实现重试尝试。
这是一篇文章的链接,该文章使用 shell 脚本等待服务就绪。
IMO 您的应用程序应该足够聪明,可以在无法建立数据库连接时重试几次。无论如何,它将使它更加健壮。
推荐阅读
- mongodb - 无法使用 Mongoose 中间件删除 Mongoose 文档
- regex - 正则表达式,查找时区 UTC 时区除外,当两者都可用时
- xml - 我们如何使用 1.0 版加入 XPATH?
- c++ - VS 2019 中未显示 Direct3D Win32 游戏模板
- python - pygraphviz 或 networkx:获取给定节点的所有子图的名称
- python - 如何添加一个列来计算是否至少有一条记录?
- git - 将 Overleaf 项目的 Git 推送到除 master 之外的其他分支
- javascript - 如何在 reactjs 中获取图像 api?
- wcf - 客户端代理建立双工 TCP 连接。只能制作5个代理客户端实例
- pandas - pandas groupby 之后的访问列