docker-compose在docker python:3中缺少环境变量
作者:互联网
虽然我的配置看起来不错,但是我的python:3映像似乎没有设置预期的DJANGO_SECRET_KEY,至少在Dockerfile尝试运行迁移的时候
$docker-compose config
services:
api:
build:
context: /Users/ben/Projects/falcon/falcon-backend
dockerfile: Dockerfile
depends_on:
- db
- redis
environment:
DJANGO_SECRET_KEY: 'some-secret-that-works-elsewhere'
$
$docker-compose up --build api
[...]
Step 6/7 : RUN echo `$DJANGO_SECRET_KEY`
---> Running in fbfb569c0191
[...]
django.core.exceptions.ImproperlyConfigured: Set the DJANGO_SECRET_KEY env variable
ERROR: Service 'api' failed to build: The command '/bin/sh -c python manage.py migrate' returned a non-zero code: 1
但是,最后一行
CMD python manage.py runserver 0.0.0.0:8001 –settings = falcon.settings.dev-microservice确实会根据需要启动,并设置了必要的环境变量.
# Dockerfile -- api
FROM python:3
RUN pip3 -q install -r requirements.txt
RUN echo `$DJANGO_SECRET_KEY`
RUN python manage.py migrate --settings=falcon.settings.dev-microservice # <-- why does this not work
CMD python manage.py runserver 0.0.0.0:8001 --settings=falcon.settings.dev-microservice
为什么Dockerfile的倒数第二行由于未设置环境变量而失败,而最后一个却按预期工作呢?
解决方法:
RUN仅在构建映像时使用. CMD是从映像启动容器时启动的命令.如果在构建映像时运行迁移是错误的,则说明迁移正在构建数据库,并且您希望每次在runserver之前运行它
# Dockerfile -- api
FROM python:3
RUN pip3 -q install -r requirements.txt
RUN echo `$DJANGO_SECRET_KEY`
CMD /bin/bash -c "python manage.py migrate --settings=falcon.settings.dev-microservice && python manage.py runserver 0.0.0.0:8001 --settings=falcon.settings.dev-microservice"
这是在docker中启动django的正确方法,因为您要在启动服务器时在生产环境上运行迁移.建立影像时不在电脑上…
标签:docker,docker-compose,django-migrations,python,django 来源: https://codeday.me/bug/20191025/1927807.html