简体   繁体   中英

Docker ENV for Python variables

Being new to python & docker, I created a small flask app (test.py) which has two hardcoded values:

username = "test"
password = "12345"

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"]`

How can I create a ENV variable for username & password and pass dynamic values while running containers?

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> ...

This will set the env variable within the container and these will be later read by the python script ( test.py )

More info on os.environ and docker env

In your Python code you can do something like this:

 # 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:

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:

$ 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.

I solved it by specifying the .env file explicitly in the base:

web:
    env_file:
      - .env

Not sure why, according to the docs it should just work if there's an .env file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM