【发布时间】: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