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"