Django connection with postgres by docker-compose

My django project cannot connect to the postgres database container. What should I do?

python manage.py collectstatic --noinput && python manage.py makemigrations blog && python manage.py migrate . I know that the docker launch command creates a new container, but I have more commands as one on bash in docker-compose.yml. It should work, right?

my Dockerfile :

 FROM python:3.6-alpine MAINTAINER Name < name@domain > ENV PYTHONUNBUFFERED 1 ENV INSTALL_PATH /heckblog RUN mkdir -p $INSTALL_PATH WORKDIR $INSTALL_PATH COPY requirements.txt requirements.txt # make available run pip install psycopg2 RUN apk update && \ apk add --virtual build-deps gcc python3-dev musl-dev && \ apk add postgresql-dev RUN pip3 install -r requirements.txt # add bash into alpine linux RUN apk add --update bash && rm -rf /var/cache/apk/* COPY ./heckblog . #RUN pip install . CMD gunicorn -b 0.0.0.0:8000 --access-logfile - "config.wsgi:application" 

my docker-compose.yml :

 version: '2' services: db: image: postgres:alpine environment: POSTGRES_USER: blogdmin POSTGRES_PASSWORD: password POSTGRES_DB: heckblog PGDATA: /tmp/pgdata volumes: - postgres_data:/tmp/pgdata web: build: . command: > bash -c "sleep 10 && python manage.py collectstatic --noinput && python manage.py makemigrations blog && python manage.py migrate && echo \"from django.contrib.auth.models import User; User.objects.create_superuser('admin', ' admin@example.com ', 'pass')\" | python manage.py shell && gunicorn -b 0.0.0.0:8000 --access-logfile - --reload \"config.wsgi:application\"" volumes: - ./heckblog:/heckblog depends_on: - db environment: IN_DOCKER: 1 ports: - "80:8000" volumes: postgres_data: 

settings.py :

 ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'heckblog', 'USER': 'blogdmin', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', # default port } } ... 

The output of docker-compose up --build :

 web_1 | TCP/IP connections on port 5432? web_1 | could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | heckblog_web_1 exited with code 1 

I use: Windows 10 Docker 17.03.0-ce-win1- (10296) docker-compose version 1.11.2 Django == 1.10.6 psycopg2 == 2.7.1.

thanks for answers

+5
source share
1 answer

Each container in docker gets its own hostname and IP by default. When compose spins containers for you, it also puts all containers on the default network to allow DNS-based discovery.

This means that your database is not accessible on localhost, but you can contact it by the service name "db". Change this line in settings.py parameters:

  'HOST': 'localhost', 

in

  'HOST': 'db', 
+6
source

Source: https://habr.com/ru/post/1265490/


All Articles