1

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?

9
  • 2
    If you're running a separate docker container, you can't use 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 just db or postgres). Docker usually provides name resolution so that the ip resolves to the correct container. Commented Oct 7, 2022 at 12:41
  • Thanks for the reply, but how does my Python API get the hostname then? Hardcore it like db? And yes, usually I use localhost Commented Oct 7, 2022 at 12:48
  • You need to pass it as a configuration parameter. Environment variables are easy to set (docker 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-coding localhost is not usually correct. Commented Oct 7, 2022 at 12:59
  • In an FastAPI app you usually use BaseSettings from Pydantic and override it through .env or through an environment variable: fastapi.tiangolo.com/advanced/settings Commented Oct 7, 2022 at 13:07
  • 1
    I am using docker compose now and it works with using the postgres container name as the host in the backend. Thank you guys! Commented Oct 9, 2022 at 17:33

1 Answer 1

0

To connect to db in container from another container, here create_engine(f"postgresql://{self.user}:{self.password}@{self.host}:{self.port}")

the self.host should be your db docker container name as in docker compose. Should work like charm with postgres or other db.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.