Py学习  »  docker

docker compose-无法连接到postgres db

user1298426 • 2 年前 • 437 次点击  

我试图在Jenkins slave上运行docker compose命令,但在运行命令pytest tests/integration时失败。 该命令使用后端作为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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133273
 
437 次点击  
文章 [ 2 ]  |  最新文章 2 年前
Muhammad Hasan
Reply   •   1 楼
Muhammad Hasan    2 年前

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

larsks
Reply   •   2 楼
larsks    2 年前

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

最好的选择可能是在集成测试中添加一些重试逻辑。例如,在你的简历中添加一些东西 setup method 循环,直到能够建立成功的数据库连接。