首页 > 解决方案 > 无法使用 docker compose 通过不同容器上的 pyscog2 连接到 postgres DB 容器

问题描述

这是我的码头工人撰写

version: '2.1'
services:
  db:
    restart: always
    image: nikitph/portcastdbimage:latest
    ports:
      - "5432:5432"
    environment:
      - DEBUG = false
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

  scraper:
    build: .
    restart: always
    links:
      - db
    environment:
      - DB_HOST = db
      - BAR = FOO
    depends_on:
      db:
        condition: service_healthy
    command: [ "python3", "./cycloneprocess.py" ]

现在根据我从堆栈溢出中收集到的信息,有两个选项可以从不同的容器访问这个数据库

a) 使用环境变量

self.connection = psycopg2.connect(host=os.environ["DB_HOST"], user=username, password=password, dbname=database)

print(os.environ["DB_HOST"]) 给了我'db'。我不知道那是否是预期的

b)直接使用'db'

 self.connection = psycopg2.connect(host='db', user=username, password=password, dbname=database)

他们似乎都没有工作,因为没有数据被填充。一切都在本地工作,所以我很自信我的代码是准确的所有变量(如用户等)都经过检查和重新检查,并且它们在本地工作。非常感谢任何帮助。顺便说一句,一切都在同一个网络上。

标签: pythonpostgresqldockerdocker-composepsycopg2

解决方案


推荐阅读