Problem with creating ETL for Postgres in a container

Viewed 12

I'm learning docker and Prefect (such a bible for doing ETL flow in python). I have set up a container on a standard postgres image (uploaded some test data there ) I am trying to connect to postgres to python ''pull'' the selected data however I am getting a connection error. connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections?

Code to test the connection:

    import psycopg2

def connect():
    """ Connect to the PostgreSQL database server """
    conn = None
    try:
        # read connection parameters

        # connect to the PostgreSQL server
        print('Connecting to the PostgreSQL database...')
        conn = psycopg2.connect(host="localhost", 
    database="dvdrental",
    user="dominio",
    password="haslo"
                    )
        
        # create a cursor
        cur = conn.cursor()
        
    # execute a statement
        print('PostgreSQL database version:')
        cur.execute('SELECT version()')

        # display the PostgreSQL database server version
        db_version = cur.fetchone()
        print(db_version)
       
    # close the communication with the PostgreSQL
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
            print('Database connection closed.')

if __name__ == '__main__':
    connect()

docker compose file:

version: "3"

volumes:
  pgdata:  

services:
  database:
    image: postgres
    volumes:
      - pgdata:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: djagoda
      POSTGRES_DB: mydb
      POSTGRES_PASSWORD: Dominik17
    networks:
      - net

  panel:
    image: adminer
    networks:
      - net
    ports:
      - 8080:8080
networks:
  net:  
0 Answers
Related