Postgresql 无法从另一个容器连接到Postgres容器
这个问题已经被问了很多次,但这些解决方案对我来说并不适用 我用这个Postgresql 无法从另一个容器连接到Postgres容器,postgresql,docker,flyway,Postgresql,Docker,Flyway,这个问题已经被问了很多次,但这些解决方案对我来说并不适用 我用这个docker compose.yml文件创建了一个Postgres和一个AppServer容器 version: "3.7" services: db: image: postgres:alpine container_name: db environment: POSTGRES_USER: user POSTGRES_PASSWORD: password
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
编辑::因此,如果我等待一段时间后从docker exec-it api bash执行flyway migrate
,一切正常。我认为上面发生的事情是,我的flyway migrate
命令甚至在数据库准备就绪之前就已经运行了
为什么会这样?因为我已经指定了依赖项,所以我的API容器应该只在数据库完全启动时启动。但情况似乎并非如此。将数据库容器指定为依赖项并不能保证它在其他服务/容器之前就准备好了。它只保证它将在您的其他服务之前启动 解决此问题的一种方法是,在启动过程中未能连接到数据库时,在API应用程序中实现重试尝试 下面是一篇使用shell脚本等待服务准备就绪的文章的示例
在我看来,当应用程序无法建立数据库连接时,它应该足够智能,可以重试几次。无论如何,这将使它更加健壮。这实际上并没有描述如何解决问题。询问者应该在其代码或容器环境中进行哪些更改?