python – 通过docker-compose连接到postgres的Django

我的django项目无法连接到postgres数据库容器.我该怎么办?

它崩溃了命令python manage.py collectstatic –noinput&& python manage.py makemigrations blog&& python manage.py migrate.
我知道docker run命令会创建一个新容器但我有更多命令
一个由bash在docker-compose.yml中.它应该有效,不应该吗?

我的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"

我的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
    }
}

...

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

我用:
Windows 10
Docker 17.03.0-ce-win1-(10296)
docker-compose版本1.11.2
Django的== 1.10.6
psycopg2 == 2.7.1.

谢谢你的回答

最佳答案
默认情况下,docker中的每个容器都有自己的主机名和IP.当compose为您旋转容器时,它还默认将所有容器放在网络上以允许基于DNS的发现.

这意味着您的数据库无法在localhost上访问,但您可以通过服务名称“db”访问它.在settings.py中更改此行:

    'HOST': 'localhost',

至:

    'HOST': 'db',

转载注明原文:python – 通过docker-compose连接到postgres的Django - 代码日志