启动 Docker-compose 时更改 psycopg2.connect 中的数据库主机

问题描述 投票:0回答:1

我有 app.py ('collect_weather.py') 和 func main()。 当我在本地启动 app.py 时,一切正常。但是如果我运行 docker-compose,则会出现错误。使用正在运行的容器 psycopg2.connect(host='localhost') 进行访问是一个错误,因为我必须以容器 host='db' 的名称访问数据库。但我想在本地运行时使用“localhost”,在容器中运行时使用“db”而不更改代码。 链接:“db:localhost”由于某种原因不起作用。

也许你会看到问题...

from backend.settings import DATABASES
HOST = DATABASES['default']['HOST']

def main():
    con = psycopg2.connect(
        user='postgres',
        password='password',
        host=HOST,
        database=DB_PATH)

数据库设置:

from dotenv import load_dotenv
load_dotenv()

    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'pg_db_weather',
    'USER': 'postgres',
    'PASSWORD': 'password',
    'HOST': os.getenv('DB_HOST', 'localhost'),
    'PORT': 5432,

.env

POSTGRES_USER=postgres
POSTGRES_PASSWORD=password
POSTGRES_DB=pg_db_weather
DB_HOST=localhost
DB_PORT=5432

Dockerfile:

FROM python:3.9

WORKDIR /app

COPY . /app

RUN pip install -r requirements.txt --no-cache-dir

CMD ["python", "/app/collect_weather.py"]

docker-compose:

version: '2.18'

volumes:
  pg_db_weather:

services:
  db:
    image: postgres:13.10
    env_file: .env
    volumes:
      - ./pg_db_weather:/var/lib/postgresql/data
    ports:
      - 5432:5432
    healthcheck:
      test: [ "CMD-SHELL", "pg_isready -U postgres" ]
      interval: 5s
      timeout: 5s
      retries: 5

  backend:
    build: .
    env_file: .env
    links:
      - "db:localhost"
    depends_on:
      db:
        condition: service_healthy

错误:

...
backend-backend-1  |     con = psycopg2.connect(
backend-backend-1  |   File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect
backend-backend-1  |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
backend-backend-1  | psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
backend-backend-1  |    Is the server running on that host and accepting TCP/IP connections?
backend-backend-1  | connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address
backend-backend-1  |    Is the server running on that host and accepting TCP/IP connections?
backend-backend-1  |
backend-backend-1 exited with code 1
python docker docker-compose psycopg2
1个回答
0
投票

我找到了解决方案的想法在这里

在 Dockerfile 中添加:

ENV HOST=db

在app.py中添加:

import os

CONTAINER_HOST = os.environ.get('HOST')

if CONTAINER_HOST:
    HOST = CONTAINER_HOST

所以在我的函数中

psycopg2.connect(host=HOST)
使用设置中的HOST='localhost' -> .env 但是当容器使用 Dockerfile 中的 HOST='db' 启动功能时。

© www.soinside.com 2019 - 2024. All rights reserved.