Tim Luka
Tim Luka

Reputation: 481

How to build a docker image from an existing flask project?

I have a flask project running on Pycharm

flask-app\
  app\
     Database.py
     static\
     tempalates\
         home.html
         objects.html
         template.html
     app.py
     requirements.txt
  ven\
  Dockerfile

I would like to dockerize the existing project in pycharm. I have tried to add new interpreter as in here, Docker-Compose: Getting Flask up and running but I did not work.

I have created docker file and tried to run it within the container, and here's what I got:

web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
web_1  |     __import__(module_name)
web_1  |   File "/opt/project/app/app.py", line 4, in <module>
web_1  |     from app import Database
web_1  | ImportError: cannot import name 'Database' from 'app' (/opt/project/app/app.py)

Obviously, There is something wrong with recognising the folder app where the app.py exists.

Here's my docker file configuration:

FROM python:3
EXPOSE 5000
MAINTAINER Khalil Mebarkia
COPY app /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD python app.py

And the app.py

from flask import Flask, render_template, request
import math
from flask_bootstrap import Bootstrap
from app import Database

db = r'database.db'

app = Flask(__name__)
bootstrap = Bootstrap(app)

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0")

@app.route("app/")
def home():
    return render_template("home.html")

Upvotes: 0

Views: 454

Answers (1)

Ali Rasim Kocal
Ali Rasim Kocal

Reputation: 540

Pycharm does not create a Dockerfile or a docker-compose.yaml file, that is your responsibility. The two files are linked in the tutorial you were following:

  1. https://github.com/ErnstHaagsman/flask-compose/blob/master/docker-compose.yml
  2. https://github.com/ErnstHaagsman/flask-compose/blob/master/Dockerfile

Those files should be at your project root. In short, the Dockerfile describes the runtime environment (the image) for your application, and the compose files tells docker how to create and start this image. In most real-life cases, both these files are going to be modified to fit your needs, and are therefore hard to autogenerate.

Then you can follow the section Configuring Pycharm to set up a remote interpreter (Docker).

Couple more things to notice:

  1. Docker interpreter is only supported in the professional edition of pycharm.
  2. You also have to install and start docker and docker-compose yourself.

Upvotes: 2

Related Questions