Context
I need to connect from inside a compose service to a PostgreSQL (10) database which is on my local host machine (Ubuntu 18.04).
Description of the errors
I have set service > app > build >
to network: host
in my compose file:
version: '3.8'
app:
image: myservice:0.0.1
restart: unless-stopped
build:
context: .
dockerfile: Dockerfile
network: host
The Dockerfile is build FROM python:3.9.1-slim-buster
.
Then, from inside my compose service (docker exec -it composefilefolder_app_1 bash
) I try to connect to a PostgreSQL database on the host machine with psycopg2
(after having started python
):
import psycopg2
DBPARAMS = {
'user': 'postgres',
'password': 'password',
'host': 'localhost',
'port': '5432',
'dbname': 'mydatabase'
}
conn = psycopg2.connect(**DBPARAMS)
but this returns:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
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?
Then I tried to use my host machine IP (given by ifconfig
):
import psycopg2
DBPARAMS = {
'user': 'postgres',
'password': 'password',
'host': '192.168.x.1',
'port': '5432',
'dbname': 'mydatabase'
}
conn = psycopg2.connect(**DBPARAMS)
but now I got a time-out after one minute:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection timed out
Is the server running on host "192.168.x.1" and accepting
TCP/IP connections on port 5432?
All other parameters are correct as I can connect to this database by running the same command from the host machine directly.
Question
How can I connect to my host machine PostgreSQL database from my compose service?
What else I've tried
- This thread seemed promising but it doesn't work either.
- And this one is for Mac users.
- I also tried to set
list_adressess='*'
in my local machinepostgres.conf
file AND to sethost all all 0.0.0.0/0 md5
into thepg_hba.conf
file without any changes. But if I can avoid to tweak my local PostgreSQL config that would be great. - This thread also did not help as it makes use of my local machine IP, for which the connection is timing-out as I said.