[英]Docker ENV for Python variables
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 变量并传递动态值?
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.environ and docker env有关os.environ和docker env的更多信息
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:您将使用以下命令运行 compose 文件:
$ 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.我希望这能回答你的问题。
FROM python:3 MAINTAINER <abc@test.com> ENV username=test password=12345 RUN mkdir /dir/name RUN cd /dir/name && pip3 install -r requirements.txt WORKDIR /dir/name ENTRYPOINT ["/usr/local/bin/python", "./test.py"]
I split my docker-compose into docker-compose.yml
(base), docker-compose.dev.yml
, etc., then I had this issue.我将 docker-compose 拆分docker-compose.yml
(基础)、 docker-compose.dev.yml
等,然后我遇到了这个问题。
I solved it by specifying the .env
file explicitly in the base:我通过在基础中明确指定.env
文件来解决它:
web:
env_file:
- .env
Not sure why, according to the docs it should just work if there's an .env
file.不知道为什么,根据文档,如果有.env
文件,它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.