4

I am trying to dockerize my Django-postgres app. My Dockerfile is:

FROM python:3

ENV PYTHONUNBUFFERED 1

RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/

My docker-compose.yml is:

version: '3'

services:
  web:
    build: .
    command: python app/manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
  db:
    image: postgres
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PASSWORD: password

and my settings .py has the following database code:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'password',
        'HOST': '0.0.0.0',
        'PORT': '5432',
    }
}

My db and web containers are up but when I run: docker-compose run web python manage.py migrate I am getting the error:

psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP connections on port 5432?

How can I make my containers communicate?

1 Answer 1

8

change HOST to:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'password',
        'HOST': 'db',
        'PORT': '5432',
    }
}

0.0.0.0 is not a valid IP, beside you need to connect using the service name since compose will resolve it for you

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

8 Comments

Can I use the service name in my python code if I want to connect to db? It worked in the scenario above but failed in other places.
when I run: con = psycopg2.connect("host=db dbname=postgres user=postgres password=password") I got the error: could not translate host name "db" to address: Unknown host
if that runs in one of the two containers from the compose , then yes that should work.
It worked when I ran it from the container. Thanks a lot @LinPy !
if you want to use that outside the container just use : localhost:5432
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.