gpt4 book ai didi

python - 无法连接到基于postgres的容器

转载 作者:行者123 更新时间:2023-12-02 20:48:27 26 4
gpt4 key购买 nike

我是 docker 容器的新手。我正在尝试在 Circle CI 上自动对我的 Flask 应用程序进行单元测试。但是它无法连接到 postgres 容器。它适用于我的本地计算机(macOS Sierra)。如果您需要更多信息来解决此问题,请告诉我。谢谢!!

docker -compose.yml

version: '3'
services:
web:
container_name: web
build: ./web
ports:
- "5000:5000"
depends_on:
- postgres
volumes:
- ./web/.:/app
tty: true

postgres:
container_name: postgres
build: ./db
ports:
- "5432:5432"

配置.yml
version: 2
jobs:
build:
machine: true

working_directory: ~/repo

steps:
- checkout

- run:
name: Install Docker Compose
command: |
sudo curl -L https://github.com/docker/compose/releases/download/1.16.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose

- run:
name: Start container and veryfy it's working
command: |
set -x
cd ~/repo/docker
docker-compose up --build -d
- run:
name: Run test
command: |
cd ~/repo/docker
docker-compose run web python tests/test_therapies.py

圈词构建日志
    connection = pool._invoke_creator(self)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/strategies.py", line 105, in connect
return dialect.connect(*cargs, **cparams)
File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 393, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
Is the server running on host "postgres" (172.18.0.2) and accepting
TCP/IP connections on port 5432?


----------------------------------------------------------------------
Ran 1 test in 0.025s

FAILED (errors=1)
Exited with code 1

最佳答案

我认为问题在于当您的网络应用程序启动时,postgres 服务没有完全启动。根据您在添加 sleep 计时器后对其工作的评论,这似乎是问题所在。

您可以运行一个名为 dadarek/wait-for-dependencies 的容器作为等待服务启动的机制(在您的情况下,postgres)。

以下是如何实现它:

1)。向 docker-compose.yml 添加新服务

  waitfordb:
image: dadarek/wait-for-dependencies
depends_on:
- postgres
command: postgres:5432

您的 docker-compose.yml 现在应该如下所示:
version: '3'
services:
waitfordb:
image: dadarek/wait-for-dependencies
depends_on:
- postgres
command: postgres:5432

web:
container_name: web
build: ./web
ports:
- "5000:5000"
depends_on:
- waitfordb
- postgres
volumes:
- ./web/.:/app
tty: true

postgres:
container_name: postgres
build: ./db
ports:
- "5432:5432"

2)。启动撰写
docker-compose run --rm waitfordb
docker-compose up -d web postgres

结果是您的 web服务现在应该等待端口 5432 在您的 postgres 容器中启动,然后再尝试启动。

关于python - 无法连接到基于postgres的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47266495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com