Docker ENV for Python variables
Within your python code you can read env variables like:
import osusername = 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:3MAINTAINER <abc@test.com>ENV username=test password=12345RUN mkdir /dir/nameRUN cd /dir/name && pip3 install -r requirements.txtWORKDIR /dir/nameENTRYPOINT ["/usr/local/bin/python", "./test.py"]