我的django项目无法连接到postgres数据库容器。我该怎么办?
它在命令时崩溃python manage.py collectstatic --noinput && python manage.py makemigrations blog && python manage.py migrate。我知道docker run命令会创建一个新的容器,但是在docker-compose.yml中,bash包含了更多命令。它应该工作,不是吗?
python manage.py collectstatic --noinput && python manage.py makemigrations blog && python manage.py migrate
我的Dockerfile:
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:
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:
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:
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',