简体   繁体   English

Docker env_file 在运行构建时不起作用

[英]Docker env_file not working when running build

I have the following docker-compose.yml :我有以下docker-compose.yml

version: '3'

services:

    website:
        build:
            context: website
        env_file: website/config/production.env

The website service corresponds to this website/Dockerfile : website服务对应这个website/Dockerfile

FROM python:2.7

RUN apt-get update

COPY src /usr/website
WORKDIR /usr/website

RUN pip install --upgrade pip
RUN pip install -r requirements.txt

RUN python manage.py migrate

I also have website/config/production.env , with several settings, such as the following:我也有website/config/production.env ,有几个设置,如下所示:

DJANGO_SECRET_KEY=

DJANGO_DATABASE_NAME=
DJANGO_DATABASE_USER=
DJANGO_DATABASE_PASSWORD=
DJANGO_DATABASE_HOST=
DJANGO_DATABASE_PORT=3306

If I run docker-compose config , the variables show properly under the environment key, but when I run docker-compose build I get如果我运行docker-compose config ,变量在environment键下正确显示,但是当我运行docker-compose build我得到

django.core.exceptions.ImproperlyConfigured: DJANGO_SECRET_KEY is not in your environment django.core.exceptions.ImproperlyConfigured:DJANGO_SECRET_KEY 不在您的环境中

That's because I have this on my settings.py file:那是因为我的settings.py文件中有这个:

def require_environ(key):
    if key in os.environ:
        return os.environ.get(key)
    raise ImproperlyConfigured('%s is not in your environment' % (key,))

So, the code is working as it should, but the variable is not defined.因此,代码正常工作,但未定义变量。 Why not?为什么不?

As @David Maze said in the comments above, you can't run migrations from a docker file.正如@David Maze 在上面的评论中所说,您不能从 docker 文件运行迁移。 The env vars are not available during the build stage, and thus the migrations must/should be run after.环境变量在构建阶段不可用,因此必须/应该在之后运行迁移。

To solve this, I created a script start.sh , as follows:为了解决这个问题,我创建了一个脚本start.sh ,如下:

#!/bin/bash
set -e

# Django: migrate
#
# Django will see that the tables for the initial migrations already exist
# and mark them as applied without running them. (Django won’t check that the
# table schema match your models, just that the right table names exist).
python manage.py migrate --fake-initial

# Django: collectstatic
#
# This will upload the files to s3 because of django-storages-redux
# and the setting:
# STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
python manage.py collectstatic --noinput

#####
# Start uWSGI
#####
/usr/local/bin/uwsgi --emperor /etc/uwsgi/django-uwsgi.ini

The script is ran as the last line of the Dockerfile :该脚本作为Dockerfile的最后一行运行:

CMD [ "/usr/start.sh" ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM