Home > Mobile >  How to connect python to postgres through docker-compose?
How to connect python to postgres through docker-compose?

Time:08-16

I can't connect muy python app to postgres all run over docker, this is 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

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

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.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

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()

CodePudding user response:

According to your edit, your DB_HOST variable is not correct, here localhost is localhost inside the python container. Your python instance (app) should point to the hostname of your db. Because docker-compose allow for refering to services with their name, you can simply do in your env file :

DB_HOST=db
  • Related