0

I am running a postgres database inside a docker container on a Windows 10 machine using Docker desktop. I would like to run postgresql queries on the database using psycopg2 but I am unable to establish connection to the database. I used the following command to run the database

docker run --name thedatabase -p 5432:5432 -e POSTGRES_PASSWORD=postgres -e POSTGRES_HOST_AUTH_METHOD=md5 postgres:13.5

I used docker inspect to get the IP address for the database. I used the following code to establish a connection with the database using psycopg2.

import psycopg2
from psycopg2 import OperationalError

def create_connection(db_name, db_user, db_password, db_host, db_port):
    connection = None
    try:
        connection = psycopg2.connect(
            database=db_name,
            user=db_user,
            password=db_password,
            host=db_host,
            port=db_port,
        )
        print("Connection to PostgreSQL DB successful")
    except OperationalError as e:
        print(f"The error '{e}' occurred")
    return connection

if __name__=="__main__":
    connection = create_connection(
    "thedatabase", "postgres", "postgres", "172.17.0.2", "5432"
)

I am getting the following error

The error connection to server at 172.17.0.2, port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections?
occurred

Any help would be appreciated. Thanks.

1 Answer 1

1

Try to replace docker ip by localhost if your python script is not executed in docker.

if __name__=="__main__":
    connection = create_connection(
    "thedatabase", "postgres", "postgres", "localhost", "5432"
)
Sign up to request clarification or add additional context in comments.

1 Comment

That worked. Thanks. Can you explain why this works and providing the actual IP didn't?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.