1

Dockerfile

FROM python:3.8

ENV PYTHONUNBUFFERED 1
ENV WORKDIR /usr/src/app

WORKDIR ${WORKDIR}

RUN pip install --upgrade pip && pip install pipenv


COPY ./Pipfile* ${WORKDIR}/

RUN pipenv lock --requirements > requirements.txt

RUN pip install -r requirements.txt

ADD . ${WORKDIR}/

docker-compose.yml

version: '3'

services:
  database:
    image: postgres:latest
    environment:
      POSTGRES_PASSWORD: development
      POSTGRES_USER: development
      POSTGRES_DB: dev_db
    ports:
      - 5432:5432
  backend:
    build: .
    command: python /usr/src/app/manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/usr/src/app
    ports:
      - 8000:8000
    depends_on:
      - database

Django database configurations

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

However, when I start docker compose, it gives the following message:

> Is the server running on host "database" (172.29.0.2) and accepting
    TCP/IP connections on port 5432?

Can anyone provide some guidance on why I'm getting this error? As far as I know both services are inside the same network

1
  • Is there anything in the database container logs about potential problems to initialize/run the database server ? Commented Jan 31, 2020 at 17:46

2 Answers 2

1

This is probably because when the Django instance is ready, Postgres is still starting up.

A common solution is to use a script like wait-for to delay the execution of a command until a service is replying on a specific host/port.

Take a look at the Docker documentation about controlling the startup order of multiple containers.

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

1 Comment

You're right I replace the command inside my backend service bash -c 'while !</dev/tcp/database/5432; do sleep 1; done; python /usr/src/app/manage.py runserver 0.0.0.0:8000' and now it is working as expected. Thank you very much.
0

I think you are missing the hostname in the yml file. See below

services:
  database:
    image: postgres:latest
    hostname: database
    environment:
      POSTGRES_PASSWORD: development
      POSTGRES_USER: development
      POSTGRES_DB: dev_db
    ports:
      - 5432:5432

1 Comment

Hello, tried to add hostmane with no luck, django app is still unable to find the database

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.