docker-compose not setting environment variables with flask docker-compose not setting environment variables with flask flask flask

docker-compose not setting environment variables with flask


I leave you an example of how to do to get the environment variables from the application.

docker-compose.yml

version: '2'services:  app:      image: python:2.7      environment:        - BAR=FOO      volumes:        - ./app.py:/app.py      command: python app.py

app.py

import osprint(os.environ["BAR"])


I personally feel that the env variables must be set with a name and value prefixed under the environment section of your docker file. At least this is what I have worked with on Kubernetes deployment yaml

env:- name: CouchDB value: "Couch DB URL"- name: "ENV Variable 1" value: 'Some value for the variable'

The you could try to exec into the pod and try to echo out the environment variable just to be sure.

As you mentioned, accessing it throught os.environ in your python script should get you going.


I also have another example:
You can pass the env variable using the Dockerfile
Like This ENV SECRET="abcdefg"In the Dockerfile.
So the complete Dockerfile will look like this:

FROM python:3.7.9LABEL maintainer_name="Omar Magdy"COPY requirements.txt requirements.txtENV SECRET="abcdefg"RUN pip install -r requirements.txtEXPOSE 5000COPY . .ENV FLASK_APP=app.pyENV FLASK_RUN_HOST=0.0.0.0ENV FLASK_ENV=developmentENV FLASK_DEBUG=0CMD ["flask", "run"]

Now in the docker-compose.yml:

version: "3.9"services:  web:    build: .    ports:      - "5000:5000"    volumes:      - "the_data_base:/db"volumes:  the_data_base:    external: true

Assuming that you have created an external volume called the "the_data_base", to store the data inside the external volume.
So, my solution suggests creating the environmental variable inside the Dockerfile, instead of inside the docker-compose file.
So you create the environmental variable at the moment of the creation of the container.
:) :)