4

I'm trying to connect to postgres docker container via psycopg2, but i keep getting the same error.

I'm doing this on jupyter (docker container), i restart several times postgres container and i change postgresql.config listen_addresses = '*' to listen_addresses = 'localhost' and it's the same error.

This is the docker run command:

docker run --name postgres -e POSTGRES_PASSWORD=xxxxxxx -d -p 5432:5432 -v $HOME/docker/volumes/postgres:/var/lib/postgresql/data  postgres

python

import psycopg2 as pg
connection = pg.connect("host=localhost dbname=easy_cleaning user=root")

I expect to connect, but i got this error:


----> 3 connection = pg.connect("host=localhost dbname=easy_cleaning user=root")

/opt/conda/lib/python3.7/site-packages/psycopg2/__init__.py in connect(dsn, connection_factory, cursor_factory, **kwargs)
    124 
    125     dsn = _ext.make_dsn(dsn, **kwargs)
--> 126     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
    127     if cursor_factory is not None:
    128         conn.cursor_factory = cursor_factory

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?
4
  • 1
    It would help if you shared the docker run command that you're using, or the docker-compose file. This is most likely a problem with the port mapping on the container. Commented Sep 3, 2019 at 17:16
  • I updated it up there Commented Sep 3, 2019 at 19:45
  • 1
    try to connect with the host's IP. Type docker inspect postgres (where postgres is the container name) and find the IPAddress. Otherwise, you can use docker-compose and use the service name as the host (but keep in mind that the API and the database should be on the same network) Commented Sep 3, 2019 at 19:57
  • Thanks that was it, now is working. Commented Sep 3, 2019 at 20:21

1 Answer 1

2

On your configuration, your container is not on localhost, Docker created a private IP to it. So you need to run:

docker inspect postgres

And look for IPAddress field to use in your connection as:

connection = pg.connect("host=<DOCKER_IP_ADDRESS> dbname=easy_cleaning user=root")

OR

You can use docker-compose to run your images as services and each service has it's name, which can be used as a hostname in your connections, like:

connection = pg.connect("host=postgres dbname=easy_cleaning user=root")

Read more here

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

Comments

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.