Flask App on Docker Image and Docker-compose.yml cannot import "app"

Issue

I tried to deploy a flask app project. When I directly docker-compose up –build is working but when I create the image and save&load to another place my same docker-compose.yml file cannot run properly. The error is cannot import "app".

working area:

  • Dockerfile

  • docker-compose.yml

  • src/app.py

not working era:

  • image.tar file(which is using for docker load)
  • docker-compose.yml

Dockerfile:

RUN mkdir /app

COPY . /app

WORKDIR /app/src

COPY requirements.txt /app/src/requirements.txt

RUN pip install -r requirements.txt


ENV FLASK_APP="app.py"

EXPOSE 5005

CMD python -u -m flask run --host=0.0.0.0

docker-compose.yml:


version: "3"

services:
  app:
    restart: unless-stopped
    build: .
    ports:
      - "5005:5005"
    volumes:
      - .:/app
    expose:
      - 5005

src/app.py:

if __name__ == "__app__":
    # start up api
    app.run(port=5005, debug=True, host="0.0.0.0")

The result of docker-compose up on the not working era is Error:cannot import "app".

Solution

The docker-compose.yml file wouldn’t work on a machine where the application code doesn’t exist because of the volume mount defined here

    volumes:
      - .:/app

This volume mount will tell Docker to take whatever’s in the . directory of the host machine and mount it to the /app directory on the container. In this case, on your machine where the app doesn’t run, you mentioned that the application code doesn’t exist in this directory, so it would make sense that the application doesn’t run. If you remove the volume mount from the docker-compose.yml file on the second machine and try to run the container again, things should work normally as long as your application code is all copied over to the image correctly. You can read more about Docker volumes here.

Answered By – Ryan Cahill

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published