【问题标题】:How do I set environment variables in a python script using a dockerfile?如何使用 dockerfile 在 python 脚本中设置环境变量?
【发布时间】:2020-11-21 03:39:05
【问题描述】:

我正在尝试从 docker 容器运行一个简单的 hello world 程序。我想要做的是显示我传递给环境变量的自定义消息。如果没有任何东西传递给环境变量,那么程序应该只显示一条默认消息“Hello World!”。我已经在我的 dockerfile 中创建了一个环境变量,我正在尝试使用 --env-file 标志在我的环境变量文件中覆盖该变量。但是,我不确定设置环境变量的正确语法是什么,因为我得到“无效语法”。

以下是我的文件:

Dockerfile

FROM python:3
ADD main.py /
ENV MESSAGE "Hello World!"
CMD ["python3", "./main.py"]

env_file

MESSAGE="Goodbye World!"

main.py

# simple hello world program
print($MESSAGE)

这就是我构建和运行容器的方式

docker build -t example -f Dockerfile .
docker run --env-file=env_file --rm --name example example

【问题讨论】:

  • 请发布完整的回溯。虽然我怀疑它在抱怨$MESSAGE(这,afaik,不是有效的python语法)。
  • 如果需要获取环境变量,需要先import os再做print(os.environ.get("MESSAGE"))
  • 除了其他 cmets 和公认的答案之外,我不禁想知道您为什么不尝试在本地工作站/服务器上运行程序。如果你这样做了,你就会意识到你的 Python 程序在语法上是无效的。

标签: python docker syntax environment-variables containers


【解决方案1】:

将您的 main.py 更改为:

import os

print(os.environ['MESSAGE'])

不支持在 Python 中使用 $ 访问环境变量,这也是无效的 Python 语法。

请注意,如果没有这样的环境变量,这将引发异常,因此您可能需要使用 os.environ.get('MESSAGE') 并检查 None 或在这种情况下进行一些错误处理。

【讨论】:

  • 这正是我所需要的。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
  • 2012-01-12
  • 2018-04-02
  • 1970-01-01
  • 2014-07-18
  • 2018-05-11
  • 1970-01-01
相关资源
最近更新 更多