When running containers, the server cannot connect to the database

Question:

I’ve got an issue where my Fastapi app image can’t connect to a database that’s also in a container
But if you turn on the database and run the application not through docker, then everything works and the connection to the database is established
Here is docker

This is my Dockerfile

FROM python:3.9

ENV PYTHONPATH "${PYTHONPATH}:/"
ENV PORT=8000

RUN pip install --upgrade pip

COPY ./requirements.txt .

RUN pip install --no-cache-dir --upgrade -r requirements.txt

COPY ./app /app

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

This is my docker-compose

version: "3.8"

services:
  app:
    build: .
    env_file:
      - .env
    ports:
      - "8000:8000"
    depends_on:
      - database


  database:
    image: postgres:12
    env_file:
      - .env
    ports:
      - "5432:5432"

This is error, that I’m getting

...
2023-03-20 11:52:17 sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
2023-03-20 11:52:17     Is the server running on host "localhost" (127.0.0.1) and accepting
2023-03-20 11:52:17     TCP/IP connections on port 5432?
2023-03-20 11:52:17 could not connect to server: Cannot assign requested address
2023-03-20 11:52:17     Is the server running on host "localhost" (::1) and accepting
2023-03-20 11:52:17     TCP/IP connections on port 5432?
2023-03-20 11:52:17 
2023-03-20 11:52:17 (Background on this error at: https://sqlalche.me/e/20/e3q8)
Asked By: Dronikon

||

Answers:

Your database is not running on localhost in your container, it’s running in a separate container, which will be available on the hostname database (same as the docker compose service name). So you should change your connection string from postgresql://user:pass@localhost:5432/dbname to postgresql://user:pass@database:5432/dbname.

Answered By: M.O.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.