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)
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
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).
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.
You might consider the following suggestions:
Ensure you use
python-dotenv
to load the.env
file in your applicationVerify
.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:gcloud
command line tool, as Cloud Run doesn’t use.env
files directly.