Docker ENV for Python variables

58,256

Solution 1

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

Solution 2

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.

Solution 3

FROM python:3

MAINTAINER <[email protected]>

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"]
Share:
58,256
Abraham Dhanyaraj Arumbaka
Author by

Abraham Dhanyaraj Arumbaka

Updated on July 12, 2020

Comments

  • Abraham Dhanyaraj Arumbaka
    Abraham Dhanyaraj Arumbaka almost 4 years

    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?