Home > Blockchain >  New Dockerfile can't use .env file to read environment variables in Python
New Dockerfile can't use .env file to read environment variables in Python

Time:10-11

I'm in the process of changing my dockerfile for a python script of mine from using a requirements.txt file to using pipenv & multi stage builds. I store the env variables in a .env file and then import os and use the os.environ.get function to read them. I'm having issues with environment variables getting to work with my new dockerfile. Below are examples of what's going on.

1st dockerfile where os.environ.get('my_env_var') works in the python script and returns a value

FROM python:3.8-slim as builder

WORKDIR /app

COPY . /app

RUN pip install -r requirements.txt

CMD ["python3", "app.py"]

2nd dockerfile where os.environ.get('my_env_var') doesn't work and returns None for everything. I've entered the container and confirmed the .env file is still there and in the same directory as the app.py file by doing a ls -a in the container and i ran cat .env to ensure the values are still there.

I've copied most of this code from a tutorial post, it seems to work fine for my use case.

FROM python:3.8-slim as base

# Setup env
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONFAULTHANDLER 1


FROM base AS python-deps

# Install pipenv and compilation dependencies
RUN pip install pipenv
RUN apt-get update && apt-get install -y --no-install-recommends gcc

# Install python dependencies in /.venv
COPY Pipfile .
COPY Pipfile.lock .
RUN PIPENV_VENV_IN_PROJECT=1 pipenv install --deploy


FROM base AS runtime

# Copy virtual env from python-deps stage
COPY --from=python-deps /.venv /.venv
ENV PATH="/.venv/bin:$PATH"

# Create and switch to a new user
RUN useradd --create-home appuser
WORKDIR /home/appuser
USER appuser

# Install application into container
COPY . .

# Run the application
CMD ["python3", "app.py"]

I'm not familiar enough with Linux/dockerfiles/env variables to know if I'm like resetting something that would make it so i can no longer automatically use the .env file to read in env variables with the os.environ.get function. Maybe it's getting screwed up because there are ENV commands in there? If anyone has any info I'd appreciate it!

CodePudding user response:

As far as I know ENV variables are set in the run command independently if the .env file is present in the image or not.

When running docker image, you should specify which .env file you wish to have: docker run --env-file=path/to/env/file image:tag

You could also set up individual env variables: --env ENVVARIABLE1=foobar

Similarly if you run with docker-compose, use env_file

  • Related