[Python] How to connect to Postgres docker container via python

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to use the postgresql docker container to create some integration tests but trying to connect fails. I added a password because if I do not I get a different error about it requiring a password.

    import psycopg2

    db = psycopg2.connect(dbname='pytest', user='pytest', password='pytest', host='0.0.0.0', port='5432')


    Error:

    Traceback (most recent call last):
    File "/home/<user_name>/<directory_name>/temp.py", line 26, in <module>
    db = psycopg2.connect(dbname='pytest', user='pytest', password='pytest', host='0.0.0.0', port='5432')
    File "/home/<user_name>/anaconda3/envs/gdg/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
    psycopg2.OperationalError: connection to server at "0.0.0.0", port 5432 failed: FATAL: password authentication failed for user "pytest"
    connection to server at "0.0.0.0", port 5432 failed: FATAL: password authentication failed for user "pytest"


    Compose File:

    services:
    psql_db:
    image: postgres
    restart: always
    shm_size: 128mb
    environment:
    POSTGRES_USER: pytest
    POSTGRES_PASSWORD: pytest
    POSTGRES_HOST_AUTH_METHOD: trust


    pb_hba.conf of container:

    # TYPE DATABASE USER ADDRESS METHOD

    # "local" is for Unix domain socket connections only
    local all all trust
    # IPv4 local connections:
    host all all 127.0.0.1/32 trust
    # IPv6 local connections:
    host all all ::1/128 trust
    # Allow replication connections from localhost, by a user with the
    # replication privilege.
    local replication all trust
    host replication all 127.0.0.1/32 trust
    host replication all ::1/128 trust

    # warning trust is enabled for all connections
    # see https://www.postgresql.org/docs/17/auth-trust.html
    host all all all trust


    What am I missing?

    Continue reading...

Compartilhe esta Página