3

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()
3
  • What python code to you use to connect to sql alchemy ? Are you using something based on DB_HOST ? Commented Aug 14, 2022 at 22:40
  • hi, sami, thx to reply, yes, I've added the python code that I use Commented Aug 14, 2022 at 22:46
  • var.format() doesn't edit var in place, rather it returns a new result with the replacements (which you throw away) while leaving var unchanged. Commented Aug 15, 2022 at 2:35

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.