用于 Python 变量的 Docker ENV [英] Docker ENV for Python variables
问题描述
刚接触 python &docker,我创建了一个小烧瓶应用程序 (test.py),它有两个硬编码值:
Being new to python & docker, I created a small flask app (test.py) which has two hardcoded values:
username = "test"
password = "12345"
我能够从以下 Dockerfile 创建一个 Docker 镜像并运行一个容器:
I'm able to create a Docker image and run a container from the following 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"]`
如何为用户名和创建 ENV 变量?运行容器时输入密码并传递动态值?
How can I create a ENV variable for username & password and pass dynamic values while running containers?
推荐答案
在你的 python 代码中,你可以读取环境变量,例如:
Within your python code you can read env variables like:
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> ...
这将在容器内设置 env 变量,这些变量稍后将被 python 脚本(test.py
)读取
This will set the env variable within the container and these will be later read by the python script (test.py
)
这篇关于用于 Python 变量的 Docker ENV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!