Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 320
Abraham Dhanyaraj Avatar asked Apr 11 '18 09:04

Abraham Dhanyaraj


People also ask

How do I pass environment variables to docker 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' ...

Does docker use .env file?

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.

How can I see docker environment variables?

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.


1 Answers

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

like image 199
urban Avatar answered Oct 05 '22 18:10

urban