简体   繁体   中英

Docker- django throws error while connecting to postgres: psycopg2.OperationalError: could not connect to server: Connection refused

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?

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

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