skip to Main Content

Description

I am trying to deploy my Flask web app to Google Cloud Run, but the Docker is not reading the .env file that contains the API key. The following image is my project directory. (requirements.txt containing python-dotenv package is just below the readMe.md)

img1

Dockerfile

FROM python:3.11-slim

ENV PYTHONUNBUFFERED True

ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./

# Install production dependencies.
RUN pip install --no-cache-dir --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt
RUN pip install Flask gunicorn

CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app

docker-compose.yml

services:
  flask_app:
    build:
      context: .
      dockerfile: Dockerfile.action
    environment:
      - API_KEY=${API_KEY}

I have almost zero experience in Docker so I’m not sure if I have configured the above files right. I would be grateful for your guidance to solve this issue.

2

Answers


  1. You need to ensure that your requirements.txt file has python-dotenv package. So that you should be able to read .env files. Hence add python-dotenv into your requirments.txt file.

    Secondly make .env file and use COPY Command to copy it in your Dockerfile (Although this will be unsafe way of doing things… Can be done for Testing purpose).

    COPY .env .env
    

    For Production Environment:

    It is recommended to us Google Cloud Run -> (Your Service Name ) -> Edit & Deploy New Revision -> Environment variables

    You can go there and define your API_Key over there and deploy it in cloud run it will be able to pick it up.

    Login or Signup to reply.
  2. You might consider the following suggestions:

    • Load the environment variables in your Flask app

    Ensure you use python-dotenv to load the .env file in your application

    from dotenv import load_dotenv
    load_dotenv()
    
    • Verify .env file in Docker: Make sure your .env file isn’t ignored in the .dockerignore file and is present in the project directory.

    • Use env_file in docker-compose.yml:

    Add an env_file section to reference your .env file:

    services:
      flask_app:
        env_file:
          - .env
    
    • Set environment variables for Cloud Run: When deploying to Google Cloud Run, set your environment variables via the Google Cloud Console or the gcloud command line tool, as Cloud Run doesn’t use .env files directly.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search