Connect to postgres database on your local machine (mac) from a docker container (through docker-compose)
I’d spend a couple of nights trying to connect an API running in a docker container to a postgres database running in my local machine. The docker docs were a help, however when I tried to connect to the db I kept receiving the following error:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
The API was in FastAPI and using sqlalchemy.
To enable the connection you need to do one of 2 things…
In your docker-compose.yml file add the following
extra_hosts:
- "host.docker.internal:host-gateway"
This tells the internal docker network to look for the localhost of the machine. This was fine however I was still getting the Is the server running on host “localhost” error.
There was one final step, and that was the database URL.
My local database URL in my .env file was:
DATABASE_URL=postgresql+psycopg2://postgres:postgres@localhost/dev_app_db
From within your docker application, you need to change this to the following:
DATABASE_URL=postgresql+psycopg2://postgres:postgres@host.docker.internal/dev_app_db
Bingo, the host.docker.internal instead of localhost fixed it… !