0

I have a function that creates connection to my database that would work when I ran my original main python script in debugger. After I created a dockerfile and docker-compose file and put the project in a container, it no longer can connect. Here is the function I used:

# Create connection to Database
def create_connection(host, dbname, user, password):
    print(host, dbname, user, password)
    try:
        conn = psycopg2.connect("host={} dbname={} user={} password={}".format(host, dbname, user, password))
        conn.set_session(autocommit=True)
    except psycopg2.Error as e:
        print("Error: Could not make connection to the Postgres database")
        print(e)

    #Use the connection to get a cursor that can be used to execute queries.
    try:
        cur = conn.cursor()
    except psycopg2.Error as e:
        print("Error: Could not get cursor to the Database")
        print(e) 

    return conn, cur

My error message:


Error: Could not make connection to the Postgres database
connection to server at "127.0.0.1", port 5432 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?

I have tried to configure my docker-compose.yml file like so:

version: '3.4'

networks:
  network1:
    name: my-network
    attachable: true
    ipam:
      driver: default
      config:
        - subnet: 172.18.0.0/16
          ip_range: 172.18.5.0/24
          gateway: 172.18.0.1

services:
  tft:
    image: tft
    build:
      context: .
      dockerfile: ./Dockerfile
    network_mode: host
    postgres:
      image: postgres:14.1-bullseye
      environment:
        POSTGRES_PASSWORD: "*********"
      ports:
        - "5433:5432"
      networks:
        - network1
      extra_hosts:
        - "host.docker.internal:host-gateway"
ichiu
  • 1
  • Are you trying to run PostgreSQL in a container, or do you have an existing database on the host you're trying to reuse? Your Compose setup has some indentation problems; can you [edit] the question to correct the YAML? – David Maze Jun 23 '23 at 20:48
  • Hi @DavidMaze, I'm very new to docker and learning it on my own and not sure what indention problems are in the YAML. Can you tell me where it's incorrect. Also, no, I am not trying to run Postgres in a container and do have an existing database outside on my local 127.0.0.1 . Would you suggest that I run postgres inside the container instead? – ichiu Jun 23 '23 at 21:12
  • A database in a container can be a more convenient approach, particularly since it's very easy to destroy and recreate it if you need to. The topic of connecting a container application to a host database is very well covered in the linked question, however. (Of note the container 127.0.0.1 is different from the host 127.0.0.1.) – David Maze Jun 23 '23 at 21:19

0 Answers0