【发布时间】:2021-08-11 03:17:38
【问题描述】:
我正在使用 docker 和 postgresql 做一个 django API,我设置了一个 docker compose 文件来使用一个 db 网络,它是一个 postgresql 映像和一个应用程序网络,它是我的 django 应用程序。我不知道发生了什么(我按照教程进行操作)但我的配置不起作用,它在 django 上给我一个错误,即数据库不存在。
这是文件:
docker-compose.yml
version: "3"
services:
app:
build:
context: .
ports:
- "8000:8000"
volumes: # Any change made on the project will be reflected on the container
- ./app:/app
command: >
sh -c "python manage.py wait_for_db &&
python manage.py migrate &&
python manage.py runserver 0.0.0.0:8000"
environment:
- DB_HOST=db
- DB_NAME=recipe
- DB_USER=postgres
- DB_PASS=supersecretpassword
depends_on:
- db
db:
image: postgres:10-alpine
environment:
- POSTGRES_DB=recipe
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=supersecretpassword
Dockerfile
FROM python:3.7-alpine
LABEL maintainer="trolliama"
# Recommended - Don't Allow the python buffer the outputs
ENV PYTHONUNBUFFERED 1
COPY ./requirements.txt /requirements.txt
# Dependencies to run postgresql
# apk it's the packege install of alpine like: apt
# apk add == apt install
RUN apk add --update --no-cache postgresql-client
RUN apk add --update --no-cache --virtual .tmp-build-deps \
gcc libc-dev linux-headers postgresql-dev
RUN pip install -r /requirements.txt
RUN apk del .tmp-build-deps
RUN mkdir /app
# Changes for the app dir
WORKDIR /app
COPY ./app /app
# By default the docker uses the root user to run the container so..
# Create a user with for just run the application
RUN adduser -D user
# Changes to the user
USER user
settings.py
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"HOST": os.environ.get("DB_HOST"),
"NAME": os.environ.get("DB_NAME"),
"USER": os.environ.get("DB_USER"),
"PASSWORD": os.environ.get("DB_PASS"),
}
}
requirements.txt
django>=2.1.3,<2.2.0
djangorestframework>=3.9.0, <3.10.0
psycopg2>=2.7.5,<2.8.0
flake8>=3.6.0,<3.7.0
所以这是配置,在教程中我还设置了这个 django 自定义命令,它只检查数据库是否启动并存在(wait_for_db)。
wait_for_db.py
import time
from django.db import connections
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Command to wait for DB"""
def handle(self, *args, **options):
self.stdout.write("Waiting for database...")
db_conn = None
while not db_conn:
try:
db_conn = connections["default"].cursor()
self.stdout.write("db_conn: {}".format(db_conn.cursor()))
except OperationalError:
self.stdout.write("Database not available")
time.sleep(1)
self.stdout.write(self.style.SUCCESS("Database available"))
因此,当我从连接中删除此 .cursor()["default"] 时,我在执行 docker-compose up 时收到此错误,说我没有配方数据库。
django.db.utils.OperationalError: FATAL: database "recipe" does not exist
如果我不删除 cursor() 它会进入循环
所以我检查了 docker compose db 网络是否正在使用docker-compose run db 创建数据库,并转到创建的容器以获取数据库,然后是配方数据库。对正在发生的事情有任何想法吗?
【问题讨论】:
-
你能分享一下你的 requirements.txt 里面有什么吗?
-
当然,我会编辑
标签: python django postgresql docker devops