smart
smart

Reputation: 2065

database connection refused

My PostgreSQL runs under docker on port 5432.

docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
f7464f480dd3        postgres            "docker-entrypoint..."   6 hours ago         Up 3 minutes        5432/tcp            core_postgres

This is an official postgres container with some custom user and database created.

I'm using psycopg2 for connection:

import psycopg2
conn = "host='localhost' dbname='username' user='username' password='password'"
psycopg2.connect(conn)

But it raises:

Traceback (most recent call last):
  File "check_postgres.py", line 3, in <module>
    psycopg2.connect(conn)
  File "/Users/pivanchy/startup/venv/lib/python2.7/site-packages/psycopg2/__init__.py", line 130, 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" (::1) and accepting
TCP/IP connections on port 5432?
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?

I've checked both: pg_hba.conf and postgresql.conf files and it looks like there is nothing strange there.

P.S. I can't also connect to this port via telnet:

telnet localhost 5432

Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
telnet: Unable to connect to remote host

What is wrong? My container is still running without errors in logs.

Upvotes: 0

Views: 913

Answers (1)

dvnguyen
dvnguyen

Reputation: 3022

You need to map a port of localhost to the port 5432 of the container with the -p option: docker run -p 5432:5432 [Other Options] postgres.

After that, the PORTS column in docker ps should show something like this: 0.0.0.0:5432->5432

Upvotes: 1

Related Questions