skip to Main Content

i have a problem connecting to my postgres. It is running in my Docker properly but i am not able to connect via python to that container. Additionally i get no error message. "e" is empty. Any idea why it doesnt work? The container is running locally on my machine.

import psycopg2

try:
    conn = psycopg2.connect(
        host="localhost",
        database="my_database",
        user="postgres",
        password="postgres"
    )
    print("Verbindung zur PostgreSQL-Datenbank erfolgreich hergestellt.")
except Exception as e:
    print("Exception")
    print(e)
    conn = None

YML:

version: '3.7'
services:
  postgres:
    image: postgres
    container_name: my_postgres_container
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: my_database
    ports:
      - "5432:5432"


2

Answers


  1. Chosen as BEST ANSWER

    I tried a different Port and suddenly it was working ...


  2. As you program doesn’t run in the same container, you have to use the container name for the connection:

    import psycopg2
    
    try:
        conn = psycopg2.connect(
            host="my_postgres_container",
            database="my_database",
            user="postgres",
            password="postgres"
        )
        print("Verbindung zur PostgreSQL-Datenbank erfolgreich hergestellt.")
    except Exception as e:
        print("Exception")
        print(e)
        conn = None
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search