I'm trying to connect a python flask application to a database inside a postgres docker container.
I have the below database.conf:
POSTGRES_USER=testdbuser
POSTGRES_PASSWORD=testdbpass
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=testdb
and config.py:
import os
user = os.environ['POSTGRES_USER']
password = os.environ['POSTGRES_PASSWORD']
host = os.environ['POSTGRES_HOST']
database = os.environ['POSTGRES_DB']
port = os.environ['POSTGRES_PORT']
DATABASE_CONNECTION_URI = f'postgresql+psycopg2://{user}:{password}@{host}:{port}/{database}'
and finally docker-compose.yml:
version: '3.5'
services:
database:
container_name: postgres-test
image: postgres:latest
env_file: database.conf
ports:
- 5432:5432
volumes:
- postgres-data:/var/lib/postgresql/data
volumes:
postgres-data:
The error I'm getting after docker-compose up --build -d -> export $(xargs < database.conf) -> export FLASK_APP=app.py -> flask run is:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "postgres" to address: nodename nor servname provided, or not known
5432to your local machine (localhost) but trying to connect to a different host (postgres).postgres?postgres) on your computer but sandboxed. It is not really related to the terminal you run the command on. What thedocker-composefile is doing is creating an internal network where this process has the same hostname as the service name (database). It is also forwarding the port5432to your machine's5432. So any time you connect to the port5432on your local machine, you will hit the container through the forwarded port.