I’m having a problem with connecting my Dockerized FastAPI project with my already existing PostgreSQL database which is running in its own container. When I run the API locally I am able to connect to the Postgres on localhost:5432, but when I try to run the API in Docker I can’t connect to my already existing DB. I know containers run in their own network by default but I’ve tried creating custom networks and it is still not allowing me to connect. I’ve been trying to set up my Docker compose too but I’m not sure if it’s set up correctly at this point. I’m not even sure if it’s possible.
If anyone has an example of how I can connect a Dockerized FastAPI app and a separate Postgres DB running in its own container. Please help.
Created custom networks
I created Docker compose but it created a new DB when I wanted to connect to an already existing one.
I changed the database URL in FastAPI but it didn’t work. It only works if I run FastAPI locally.
2
Answers
check connection string should be the postgres container name. not the localhost.
I mean; your fastapi connection string should be like below:
Host=YourPostgreContainer;Port=5432;Database=YourPostgreDbName;Username=YourPostgreUSer;Password=YourPostgrePassword
Example for docker-compose:
Just use:
docker compose up -d
docker compose down
Connecetion string as described in the comment above, use the contanier name