Home > Back-end >  Flask app ImportError when running on Docker
Flask app ImportError when running on Docker

Time:03-29

I have a basic Flask web app that I want to set up inside a Docker container. The following is my Dockerfile setup:

FROM python:3.8-alpine

WORKDIR /mydir

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .
ENV FLASK_APP="app.py"

CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0", "-p", "8080"]

Built the docker file with

mydir % docker build -t geode:latest .      

But when I try to run the web app through Docker, this happens:

mydir % docker run -p 8080:8080 geode:latest
 * Serving Flask app 'app.py' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
Usage: python -m flask run [OPTIONS]
Try 'python -m flask run --help' for help.

Error: While importing 'app', an ImportError was raised.

However, I can run the web app locally with the following

mydir % python3 -m flask run --host=0.0.0.0 -p 8080

So I'm not sure why I'm getting an "ImportError" when I run it via docker but not when I run the command myself.

CodePudding user response:

Probably flask cannot find the source file from which to import the app variable, or a variable called app does not exist in the source file from which to import the variable.

Check out this link to see how to launch a flaks application.

If the name of the variable or file containing the app variable is different from the standard, then you can set the FLASK_APP environment variable inside the Dockerfile to tell flask where to get what it needs.

ENV FLASK_APP=<PATH_TO_APP.PY>:<APP_VARIABLE_NAME>

CodePudding user response:

I have no idea why but rebuilding the Docker container allowed it to run properly... Maybe I had a typo in the Dockerfile that I changed after I built the container? Not sure, but I was copying the structure I used for another app - the original worked and this didn't. So there was a typo somewhere and rebuilding the container worked.

  • Related