用于 Python 变量的 Docker ENV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49770999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Docker ENV for Python variables
提问by user2153844
Being new to python & docker, I created a small flask app (test.py) which has two hardcoded values:
作为 python 和 docker 的新手,我创建了一个小烧瓶应用程序 (test.py),它有两个硬编码值:
username = "test"
password = "12345"
I'm able to create a Docker image and run a container from the following Dockerfile:
我能够创建一个 Docker 映像并从以下 Dockerfile 运行一个容器:
FROM python:3.6
RUN mkdir /code
WORKDIR /code
ADD . /code/
RUN pip install -r requirements.txt
EXPOSE 5000
CMD ["python", "/code/test.py"]`
How can I create a ENV variable for username & password and pass dynamic values while running containers?
如何在运行容器时为用户名和密码创建 ENV 变量并传递动态值?
回答by urban
Within your python code you can read env variables like:
在您的 python 代码中,您可以读取 env 变量,例如:
import os
username = os.environ['MY_USER']
password = os.environ['MY_PASS']
print("Running with user: %s" % username)
Then when you run your container you can set these variables:
然后当你运行你的容器时,你可以设置这些变量:
docker run -e MY_USER=test -e MY_PASS=12345 ... <image-name> ...
This will set the env variable within the container and these will be later read by the python script (test.py
)
这将在容器中设置 env 变量,这些变量稍后将被 python 脚本 ( test.py
)
More info on os.environand docker env
有关os.environ和docker env 的更多信息
回答by OpenBSDNinja
In your Python code you can do something like this:
在您的 Python 代码中,您可以执行以下操作:
# USERNAME = os.getenv('NAME_OF_ENV_VARIABLE','default_value_if_no_env_var_is_set')
USERNAME = os.getenv('USERNAME', 'test')
Then you can create a docker-compose.yml file to run your dockerfile with:
然后你可以创建一个 docker-compose.yml 文件来运行你的 dockerfile:
version: '2'
services:
python-container:
image: python-image:latest
environment:
- USERNAME=test
- PASSWORD=12345
You will run the compose file with:
您将使用以下命令运行撰写文件:
$ docker-compose up
All you need to remember is to build your dockerfile that you mentioned in your question with:
您需要记住的就是使用以下命令构建您在问题中提到的 dockerfile:
$ docker build -t python-image .
Let me know if that helps. I hope that answers your question.
如果这有帮助,请告诉我。我希望这能回答你的问题。