1

I have a few problems connecting to PostgreSQL from my Python application. PostgreSQL is outside the container because it's an existing database.

From outside the container, the database looks accessible:

$ nmap -p 5432 localhost
Starting Nmap 7.70 ( https://nmap.org ) at 2019-07-05 18:33 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00014s latency).
Other addresses for localhost (not scanned): ::1

PORT     STATE SERVICE
5432/tcp open  postgresql

Nmap done: 1 IP address (1 host up) scanned in 0.12 seconds

But from inside:

bash-4.4# nmap -p 5432 localhost
Starting Nmap 7.70 ( https://nmap.org ) at 2019-07-05 16:34 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000040s latency).
Other addresses for localhost (not scanned): ::1

PORT     STATE  SERVICE
5432/tcp closed postgresql

Nmap done: 1 IP address (1 host up) scanned in 0.41 seconds

I could not find any similar issues.

2

1 Answer 1

4

Just add --network="host" when running your python container:

Spin up a postgres-server real quick:

docker run --rm -d --name postgres-server -p 5432:5432 postgres

If I try to connect to it with a docker client it will fail without --network="host":

docker run --rm -it --name postgres-client postgres psql -Upostgres -h localhost
psql: could not connect to server: connection refused

With --network:

docker run --rm -it --name postgres-client --network="host" postgres psql -Upostgres -h localhost
psql (10.4 (Debian 10.4-2.pgdg90+1)
postgres=#

Cheers

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly, thanks. I had not realized that the network was containerized too.

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.