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?
With a Command Line Argument The command used to launch Docker containers, docker run , accepts ENV variables as arguments. Simply run it with the -e flag, shorthand for --env , and pass in the key=value pair: sudo docker run -e POSTGRES_USER='postgres' -e POSTGRES_PASSWORD='password' ...
env in your project, it's only used to put values into the docker-compose. yml file which is in the same folder. Those are used with Docker Compose and Docker Stack.
Fetch Using docker exec Command Here, we are executing the /usr/bin/env utility inside the Docker container. Using this utility, you can view all the environment variables set inside Docker 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With