提问者:小点点

Python在导出环境变量时抛出KeyError


我有一个奇怪的例子,我有一个secret.env文件,我把所有的环境变量都设置成这样:

秘密. 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'

当我在我的窗户上运行这个程序时,它工作得很好!

有人能帮我一下吗?


共1个答案

匿名用户

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

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