0
services:
  db:
    image: postgres
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - "5432:5432"
  backend:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    environment:
      - POSTGRES_NAME=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    depends_on:
      - db

This is the docker config. The issue is backend(Django) is not able to connect to the postgres DB. I tried with DB host as localhost and it was not able to connect.

could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?

Then I changed host to the ip address of the db container but still no success, this time it was a timeout error.

could not connect to server: Connection timed out
Is the server running on host "172.11.0.2" and accepting
TCP/IP connections on port 5432?

This is how I'm connecting to postgres.

from sqlalchemy import create_engine

engine = create_engine("postgresql+psycopg2://postgres:[email protected]:5432/postgres",
                       poolclass=QueuePool,
                       pool_size=5,
                       max_overflow=10,
                       pool_timeout=1)

I think this has definitely something to do with the two containers being different but could someone help me on how to connect to Postgres container from Django's container?

5
  • 1
    postgresql+psycopg2://psg:psg@db:5432/psg should be your connection string. As soon as two containers are on the same docker network they can access themselves with their "short" names. Commented Apr 4, 2022 at 11:44
  • tried with this, getting sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "db" to address: Name or service not known. Commented Apr 4, 2022 at 11:47
  • @VK: Explicitly create a network and attach your containers to it, then check if they can find each other. Commented Apr 4, 2022 at 11:55
  • Instead of the ip 172.11.0.2, try the ip 0.0.0.0 Commented Apr 4, 2022 at 11:57
  • @iepathos tried with that as well, got connection refused. Commented Apr 4, 2022 at 11:58

1 Answer 1

0

Any service can reach any other service at that service’s name.

In docker-compose services are exposed to each other by their name. So in the host you need to use db which is the name of database service.

For more details check docs

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.