简体   繁体   English

如何通过docker-compose将python连接到postgres?

[英]How to connect python to postgres through docker-compose?

I can't connect muy python app to postgres all run over docker, this is muy dockerfile:我无法将 muy python 应用程序连接到所有运行在 docker 上的 postgres,这是 muy dockerfile:

FROM python:3.8

RUN mkdir /app
WORKDIR /app

ADD . /app/
ADD requirements.txt requirements.txt

RUN apt update -y
RUN pip install --upgrade pip
RUN pip install -r requirements.txt

My docker-compose我的 docker-compose

version: '3'
services:
  db:
    image: postgres:13.4-alpine
    environment:
      POSTGRES_PASSWORD: secret
      POSTGRES_HOST_AUTH_METHOD: trust
    env_file:
      - .env

    ports:
      - "5432:5432"
    volumes:
      - ./database/init.sql:/docker-entrypoint-initdb.d/init.sql

  app:
    build: .
    restart: always
    depends_on:
      - db
    stdin_open: true
    tty: true
    env_file:
      - .env

and my.env file和 my.env 文件

DB_NAME=database_dev
DB_USER=postgres
DB_PASSWORD=secret
DB_HOST=localhost
DB_PORT=5432

I'm trying to connect with SQLAlchemy, and this is the error我正在尝试连接 SQLAlchemy,这是错误

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "{hostname}" to address: Name or service not known

edit编辑

add my python code for connection, the env variables that I use are from.env file添加我的 python 代码进行连接,我使用的环境变量是 from.env 文件

class DatabaseManager:

    def __init__(self):
        self.db_url = 'postgresql+psycopg2://{user}:{password}\\@{hostname}/{database_name}'
        self.db_url.format(
            user=os.environ['DB_USER'],
            password=os.environ['DB_PASSWORD'],
            hostname=os.environ['DB_HOST'],
            database_name=os.environ['DB_NAME']
        )
        self.engine = create_engine(self.db_url)

    def make_session(self):
        self.Session = sessionmaker(bind=self.engine)
        self.session = self.Session()

    def add_data(self, data):
        self.session.add(data)
        self.session.commit()

    def close(self):
        self.session.close()

According to your edit, your DB_HOST variable is not correct, here localhost is localhost inside the python container.根据您的编辑,您的 DB_HOST 变量不正确,这里的localhost是 python 容器内的 localhost。 Your python instance (app) should point to the hostname of your db.您的 python 实例(应用程序)应指向您的数据库的主机名。 Because docker-compose allow for refering to services with their name, you can simply do in your env file:因为 docker-compose 允许使用名称来引用服务,所以您可以在 env 文件中简单地执行以下操作:

DB_HOST=db

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM