首页 > 解决方案 > 无法从另一个容器连接到 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 容器应该仅在数据库完全启动时启动。但似乎并非如此。

标签: postgresqldockerflyway

解决方案


将数据库容器指定为依赖项并不能保证它会在您的其他服务/容器之前准备好。它只保证它将在您的其他服务之前启动。

解决此问题的一种方法是在启动期间无法连接到数据库时在 API 应用程序中实现重试尝试。

这是一篇文章的链接,该文章使用 shell 脚本等待服务就绪。

IMO 您的应用程序应该足够聪明,可以在无法建立数据库连接时重试几次。无论如何,它将使它更加健壮。


推荐阅读