【问题标题】:Why does Django not find my Docker-env variables?为什么 Django 找不到我的 Docker-env 变量?
【发布时间】:2019-01-26 09:47:45
【问题描述】:

我正在尝试通过 Django 配置使用不同的配置来执行名为 dockerplayground 的 Django 项目。目标是在 docker-build 命令期间通过环境变量设置配置。由于某种原因,当我启动容器并使用默认值时,Django-project 找不到 env 变量。

这是我的文件,Django-project 是一个带有空 app-skaffold 的骨架,使用“python manage.py startapp example”命令制作。

Dockerfile:

FROM python:3.6

RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get autoclean
RUN apt-get install -y \
    libffi-dev \
    libssl-dev \
    default-libmysqlclient-dev \
    libxml2-dev \
    libxslt-dev \
    libjpeg-dev \
    libfreetype6-dev \
    zlib1g-dev \
    net-tools \
    vim

RUN echo openssl version

ARG DJANGO_CONF_ARG

ENV DJANGO_CONFIGURATION=$DJANGO_CONF_ARG

RUN pip install pip --upgrade
#https://github.com/circus-tent/circus/issues/1056
RUN pip install 'tornado==4.5.3'
RUN pip install gunicorn circus

ADD requirements.txt /

RUN pip install -r requirements.txt
ADD . /

EXPOSE 8000

RUN chmod +x /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]

入口点.sh

#!/bin/bash
python manage.py makemigrations
python manage.py migrate
exec circusd circus.ini --log-level debug

exec "$@";

circus.ini

[circus]
check_delay = 5

[watcher:gunicorn]
cmd = /usr/local/bin/gunicorn
args = -b 0.0.0.0:8000 -w 2 dockerplayground.wsgi
numprocesses = 1
autostart = true
max_retry = -1
priority = 500

requirements.txt

Django==2.0.7
django-configurations

dockerplayground/wsgi.py

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dockerplayground.settings")
os.environ.setdefault('DJANGO_CONFIGURATION', "Dev")

from configurations.wsgi import get_wsgi_application

application = get_wsgi_application()

manage.py

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dockerplayground.settings")
    os.environ.setdefault('DJANGO_CONFIGURATION', "Dev")

    from configurations.management import execute_from_command_line
    execute_from_command_line(sys.argv)

dockerplayground/settings.py

import os
from configurations import Configuration
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)

class Base(Configuration):
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = 'inbt@l4iuuc0xi7qiut_*=uh3@pi8^)nq1e6o$i2#7s8mu(3#j'

    # SECURITY WARNING: don't run with debug turned on in production!
    # DEBUG = True

    ALLOWED_HOSTS = ['*']


    # Application definition

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',

        'example.apps.ExampleConfig'
    ]

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    ROOT_URLCONF = 'dockerplayground.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'dockerplayground.wsgi.application'


    # Database
    # https://docs.djangoproject.com/en/2.0/ref/settings/#databases

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }


    # Password validation
    # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]


    # Internationalization
    # https://docs.djangoproject.com/en/2.0/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True


    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.0/howto/static-files/

    STATIC_URL = '/static/'

class Prod(Base):
    DEBUG = False

class Dev(Base):
    DEBUG = True

Docker 构建命令:

docker build -t dockerplayground --build-arg DJANGO_CONF_ARG=Prod . 

Docker 运行命令:

docker run -p 8000:8000 -d  dockerplayground:latest

然后如果我去容器:

docker exec -it containerid bash

并执行 printenv 我可以看到我的环境变量设置为 Prod,但 localhost:8000 显示 debug-django 欢迎屏幕。我不知道出了什么问题,因为 Prod 根本不应该显示调试登录页面。

【问题讨论】:

    标签: python django docker environment-variables circusd


    【解决方案1】:

    我认为课程类型设置可能是问题所在。不管怎样,在你的settings.py 中试试这个,

    import os
    
    PROFILE = os.environ.get('DJANGO_CONFIGURATION', 'Dev')
    if PROFILE == 'Dev':
        DEBUG = True
    else:
        DEBUG = False

    更新

    经过大量的谷歌搜索,我找到了解决方案,

    来自documenetation of circus

    copy_env

    如果设置为true,本地环境变量将在生成它们时被复制并传递给工人。 (默认:False

    所以,你必须在 circus.ini 文件中设置 copy_env=true

    因此,您的 circus.ini 将是,

    [circus]
    check_delay = 5
    
    [watcher:gunicorn]
    cmd = /usr/local/bin/gunicorn
    args = -b 0.0.0.0:8000 -w 2 dockerplayground.wsgi
    numprocesses = 1
    autostart = true
    max_retry = -1
    priority = 500
    copy_env = true
    

    【讨论】:

    • 您好,感谢您的建议,但这会使 Django-configurations 包过时,因为使用它的优势是基于类的设置模块。详情请见django-configurations.readthedocs.io/en/stable
    • 在此之前,请尝试我的解决方案并告诉我结果
    • 我尝试将您的解决方案首先放在我的 Base-settings 类中,构建并启动了 docker-image,但结果与显示的 Debug-startpage 相同。然后我尝试将它放在 Base-class 之前,但在构建和运行图像后得到了相同的结果。
    • 我试过这个包,它按预期工作。是否可以重现错误?
    猜你喜欢
    • 2021-08-05
    • 2017-06-15
    • 2021-06-12
    • 2019-10-20
    • 1970-01-01
    • 2019-09-22
    • 2021-08-23
    • 2020-04-25
    • 2021-05-24
    相关资源
    最近更新 更多