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.

rubik
  • 8,814
  • 9
  • 58
  • 88
  • Localhost for a container is the container itself. Postgres is not running on the container that's why you can't connect. Try to connect with the hostname or ip of docker host. [More](https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach) – leopal Jul 05 '19 at 18:00
  • 1
    Possible duplicate of [From inside of a Docker container, how do I connect to the localhost of the machine?](https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach) – David Maze Jul 05 '19 at 19:30

1 Answers1

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

C. Jani
  • 156
  • 3