【问题标题】:Python throws KeyError when exporting environment variablesPython 在导出环境变量时抛出 KeyError
【发布时间】:2021-03-17 15:01:10
【问题描述】:

我有一个奇怪的情况,我有一个 secret.env 文件,我在其中设置了所有环境变量:

secret.env

export TWITTER_CONSUMER_KEY="something"
export TWITTER_CONSUMER_SECRET="something"

然后我构建了一个 docker 文件来导出所有变量并运行应用程序:

FROM python:3.8-slim-buster

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
ADD . /app

# Install the dependencies
RUN pip install -r requirements.txt

RUN find . -name \*.pyc -delete

# Export all variables
RUN /bin/bash -c "source secret.env";

# tell the port number the container should expose
EXPOSE 8083

# run the command
ENTRYPOINT ["python", "run.py"]

但是,这是抛出一个关键错误:

$ docker run --name fortweet --rm -i -t fortweet:latest bash
Traceback (most recent call last):
  File "run.py", line 1, in <module>
    from app import socketio, app
  File "/app/app/__init__.py", line 65, in <module>
    app = create_app()
  File "/app/app/__init__.py", line 38, in create_app
    my_settings = settings.TwitterSettings.get_instance()
  File "/app/app/setup/settings.py", line 47, in get_instance
    TwitterSettings()
  File "/app/app/setup/settings.py", line 14, in __init__
    self.consumer_key = os.environ["TWITTER_CONSUMER_KEY"]
  File "/usr/local/lib/python3.8/os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'TWITTER_CONSUMER_KEY'

当我在我的 Windows 上运行它时,它工作正常!

有人可以帮我吗?

【问题讨论】:

标签: python docker environment-variables dockerfile


【解决方案1】:

您可以使用docker run --env-file secret.env ... 在运行时设置环境变量。有关详细信息,请参阅 docker run 文档。

RUN 退出后,在一个RUN 命令中获取文件将不会持续存在。您也不应该在 Docker 映像中存储机密。在构建时将它们排除在外并在运行时应用它们更安全。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 2013-01-18
    • 2019-12-06
    相关资源
    最近更新 更多