'Unable to connect to Postgres DB living in one docker-compose file with django app in separate docker-compose file

I have a large monorepo Django app that I want to break into two separate repositories (1 to handle external api requests and the other to handle my front end that I plan on showing to users). I would still like to have both django apps have access to the same db when running things locally. Is there a way for me to do this? I'm running docker for both and am having issues with my front end facing django app being able to connect to the Postgres DB i have set up in a separate docker-compose file than the one I made for my front end app.

External API docker-compose file (Postgres DB docker image gets created here when running docker-compose up --build)

---
version: "3.9"
services:
  db:
    image: postgres:13.4
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres

  api:
    restart: always
    build: .
    image: &img img-one
    command: bash start.sh
    volumes:
      - .:/app
    ports:
      - "8000:8000"
    depends_on:
      - db
    env_file:
      - variables.env

Front end facing docker-compose file (This is the one I want to be able to connect to the DB above):

---
version: "3.9"
services:
  dashboard:
    restart: always
    build: .
    image: &img img-two
    volumes:
      - .:/code
    ports:
      - "8010:8010"
    depends_on:
      - react-app
    env_file:
      - variables.env

  react-app:
    restart: always
    build: .
    image: *img
    command: yarn start
    env_file:
      - variables.env
    volumes:
      - .:/app
      - /app/node_modules
    ports:
      - "3050:3050"

Below is the database configuration I have set up in the front end django app that I want to connect to the DB but I keep getting connection refused errors when I try to run python manage.py runserver

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ.get("DB_NAME", "postgres"),
        "USER": os.environ.get("DB_USERNAME", "postgres"),
        "PASSWORD": os.environ.get("DB_PASSWORD", "postgres"),
        "HOST": os.environ.get("DB_HOSTNAME", "db"),
        "PORT": os.environ.get("DB_PORT", 5432),
    }
}

Any ideas on how to fix this issue? (For reference, I've also tried changing HOST to localhost instead of db but still get the same connection refused errors)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source