'Unable to connect to postgres database running in a docker container using psycopg2

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source