简体   繁体   中英

Django cannot find database when using docker-compose

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM