如何在使用Dockerfile构建映像时读取.env文件?

时间:2018-09-27 12:49:27

标签: docker docker-compose environment-variables dockerfile

这是docker-compose build命令正在使用的Docker文件:

FROM python:3.5

ENV PYTHONUNBUFFERED 1
RUN apt-get update \
    && apt-get install -y --no-install-recommends libnewlib-arm-none-eabi avr-libc git \
    && rm -rf /var/lib/apt/lists/* \
    && pip install cryptography

RUN mkdir /code
COPY . /code/
WORKDIR /code
RUN pip install -r /code/misc/requirements.txt
RUN mkdir /static
RUN python /code/manage.py migrate
RUN python /code/manage.py collectstatic --noinput

这是docker-compose.yml中使用此Dockerfile的服务:

version: "3.5"

services:
  ...
  django:
    build:
      context: .
    command: bash -c "/code/run/gunicorn.sh"
    volumes:
      - ./static:/data/django/static
      - ./media:/data/django/media
    depends_on:
      - db
    env_file:
      - misc/envs/.env

因此,当我尝试使用docker-compose build --no-cache命令构建此组合时,即使我试图将RUN set -a && source /code/misc/envs/.env && set +a步骤明确地添加到Dockerfile

UPD

结果,我的代码在最后一个Dockerfile步骤上运行

from django.core.exceptions import ImproperlyConfigured
import os


def get_env_setting(setting, default=None):
    try:
        return os.environ[setting]
    except KeyError:
        if default is not None:
            return default
        error_msg = "Set the %s env variable" % setting
        raise ImproperlyConfigured(error_msg)

SECRET_KEY = get_env_setting('SECRET_KEY')

给我一​​个错误:

  File "/code/project/settings.py", line 34, in <module>
    SECRET_KEY = get_env_setting('SECRET_KEY')
  File "/code/project/settings.py", line 22, in get_env_setting
    raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY env variable

0 个答案:

没有答案