skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. Example for docker-compose:

    version: '3'
    services:
      postgres:
        image: postgres
        container_name: postgres
        hostname: postgres
        networks:
          default:
            aliases:
              - postgresdb
        ports:
          - 5432:5432
        environment:
          - POSTGRES_PASSWORD=${DATABASE_PASSWORD}
          - POSTGRES_DB=${DATABASE_NAME}
        volumes:
          - postgres-db:/var/lib/postgresql/data
    
      my-server:
        image: my-repo/my-image:my-tag
        ports:
          - 8000:8000
        environment:
          - DATABASE_HOSTNAME=${DATABASE_HOSTNAME}
          - DATABASE_PORT=${DATABASE_PORT}
          - DATABASE_PASSWORD=${DATABASE_PASSWORD}
          - DATABASE_NAME=${DATABASE_NAME}
          - DATABASE_USERNAME=${DATABASE_USERNAME}
        depends_on:
          - postgres
    

    Just use:
    docker compose up -d
    docker compose down
    Connecetion string as described in the comment above, use the contanier name

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search