[Python] .env is not read in docker container

Discussão em 'Python' iniciado por Stack, Maio 14, 2025.

  1. Stack

    Stack Membro Participativo

    Wrote a python script that reads a setting from .env. When working and debugging in vscode this works. I then create a container of it using docker build -t myapp. When I run this command I'm in the directory that also holds the .env file.

    I then run the container with:

    docker run -d -p 5000:5000 \
    -v "$(pwd)/.env:/app/.env" \
    -v "$(pwd)/database:/app/database" \
    myapp:latest


    It starts a flask website and I can see in the GUI that the environment var is empty. When I exec into the container, the .env is there and contains the var I need.

    In my python script I have this:

    import os
    from dotenv import load_dotenv

    load_dotenv()


    and I load the var with os.getenv('envtarif').

    Why is it I can't seem to read the environment var?

    EDIT:

    Dockerfile:

    FROM python:3.11-slim-buster
    WORKDIR /app
    COPY . /app
    RUN pip install --no-cache-dir -r requirements.txt && \
    apt-get update && \
    apt-get install -y cron

    COPY crontab /etc/cron.d/reporting-cron
    RUN chmod 0644 /etc/cron.d/reporting-cron
    RUN crontab /etc/cron.d/reporting-cron

    EXPOSE 5000
    CMD ["sh", "-c", "cron && python app.py"]


    I run the container like this: sudo docker run -d -p 5000:5000 -v "$(pwd)/.env:/app/.env" -v "$(pwd)/database:/app/database" chargelogreporter:latest

    Then sudo docker exec -it flamboyant_burnell /bin/sh

    pwd result is /app

    # ls -la
    total 132
    drwxr-xr-x 1 root root 4096 May 14 23:30 .
    drwxr-xr-x 1 root root 4096 May 14 23:30 ..
    -rw-rw-r-- 1 root root 3474 May 14 20:56 .dockerignore
    -rw-r--r-- 1 root root 568 Apr 28 20:52 .env
    drwxrwxr-x 8 root root 4096 May 14 21:40 .git
    -rw-rw-r-- 1 root root 3474 Jan 24 00:24 .gitignore
    drwxrwxr-x 2 root root 4096 May 14 21:31 .vscode
    -rw-rw-r-- 1 root root 1009 May 14 22:07 Dockerfile
    -rw-rw-r-- 1 root root 35149 Dec 23 15:08 LICENSE
    -rw-rw-r-- 1 root root 2753 May 14 21:22 README.md
    drwxr-xr-x 2 root root 4096 May 14 23:30 __pycache__
    -rw-r--r-- 1 root root 1049 May 14 23:30 app.log
    -rw-rw-r-- 1 root root 3707 May 14 22:57 app.py
    -rw-rw-r-- 1 root root 86 May 14 21:08 crontab
    drwxrwxr-x 2 1000 1000 4096 May 14 21:23 database
    drwxrwxr-x 2 root root 4096 Jan 23 23:46 download
    -rw-r--r-- 1 root root 466 Feb 4 22:01 env-example
    -rw-r--r-- 1 root root 349 May 14 22:45 requirements.txt
    -rw-rw-r-- 1 root root 1224 Apr 28 21:22 schedule.py
    -rw-rw-r-- 1 root root 15362 May 14 22:42 sharedcomps.py
    drwxrwxr-x 2 root root 4096 Apr 8 19:50 static
    drwxrwxr-x 2 root root 4096 May 14 21:31 templates


    then to prove .env is loaded correctly:

    tarif=0.32
    reportday=13

    Continue reading...

Compartilhe esta Página