【问题标题】:docker-compose - Not able to connect to postgres dbdocker-compose - 无法连接到 postgres 数据库
【发布时间】:2021-08-02 10:16:18
【问题描述】:

我正在尝试在 Jenkins slave 上运行 docker-compose 命令,但在运行命令 pytest 测试/集成时失败。 该命令使用后端作为 postgres 运行集成测试。 Dockerfile 是

version: "3.4"
services:
  test:
    build:
      context: ../..
      dockerfile: Dockerfile
    depends_on:
      - postgres_db
    environment:
      PG_UNITTEST_DB: "postgresql://testuser:testpassword@postgres_db/testdb"
    command: pytest tests/integration
  postgres_db:
    image:  postgis/postgis
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PASSWORD: testpassword
      POSTGRES_USER: testuser
      POSTGRES_DB: testdb

我得到的错误是

psycopg2.OperationalError: could not connect to server: Connection refused
 Is the server running on host "postgres_db" (172.19.0.2) and accepting
 TCP/IP connections on port 5432?

我尝试在 postgres_db 部分的 docker-compose 文件中公开端口 5432,但没有帮助。相同的代码在本地运行良好。我运行的命令是

docker-compose -f tests/integration/docker-compose.yml up --build --exit-code-from test

【问题讨论】:

  • command: bash -c 'while !</dev/tcp/postgres_db/5432; do sleep 1; done; pytest tests/integration' 这对我有用

标签: docker docker-compose


【解决方案1】:

Postgres 需要一段时间才能启动,然后才能开始为请求提供服务。您在 test 容器中的代码很可能在 Postgres 准备好之前尝试连接。

您最好的选择可能是在集成测试中添加一些重试逻辑。例如,向 yoursetup method 添加一些内容,直到它能够建立成功的数据库连接。

【讨论】:

    【解决方案2】:

    您需要定义启动服务的顺序,以便您的 postgres 容器在测试容器之前启动。详细信息可以参考文档:https://docs.docker.com/compose/startup-order/

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 2018-09-03
      • 1970-01-01
      • 2019-11-06
      • 2020-09-29
      • 1970-01-01
      相关资源
      最近更新 更多