I have three Docker containers, one everything frontend (React) related, one backend (Fastapi Python), and a Postgres database.
I connected all containers to a network via docker network connect.
My frontend is able to communicate to my backend, I also can communicate to all of my containers from my machine.
But somehow I can't access the Postgres DB via Backend.
error establishing DB connection: (psycopg2.OperationalError) could not connect to server: Connection refused
Is the server running on host "0.0.0.0" and accepting
TCP/IP connections on port 5432?
My code can't be wrong as I can connect via python database.py directly.
if __name__ == "__main__":
d = Database("0.0.0.0", 5432, "postgres", "password")
d.conn_execute("")
Here some snippets from the database class of the backend:
class Database():
def __init__(self, host, port, user, password) -> None:
self.host = host
self.port = port
self.user = user
self.password = password
def conn_execute(self, query) -> None:
try:
print(f"postgresql://{self.user}:{self.password}@{self.host}:{self.port}")
self.engine = create_engine(f"postgresql://{self.user}:{self.password}@{self.host}:{self.port}")
with self.engine.connect() as connection:
result = connection.execute(query)
for i in result:
print(i)
except Exception as e:
print(f"error establishing DB connection: {e}")
It has to be a problem with the networking itself but I don't understand what additional step it needs.
Additional information:
I played around with Docker Compose, several ports and localhost and 0.0.0.0, everything lead to the same error.
Update
After trying for several hours I installed another database (MongoDB) which works like a charm.
So I believe it's a Postgres thing?
0.0.0.0(which you shouldn't really use anyway), but use the name of your other container instead (which you haven't included, but might be something like justdborpostgres). Docker usually provides name resolution so that the ip resolves to the correct container.db? And yes, usually I uselocalhostdocker run -e) and access (os.environ) but there are definitely other options. Note that this setup will be different again if you're running it in a cloud environment with a hosted database, for example, hard-codinglocalhostis not usually correct.BaseSettingsfrom Pydantic and override it through.envor through an environment variable: fastapi.tiangolo.com/advanced/settings