Methods to Dockerize a Flask App


You probably have a Flask app that you desire to packaged in a Docker container, then you are able to do the next. The steps outlined beneath will make it easier to create the next listing tree:

└── flaskapp
        ├── Dockerfile
        ├── app.py
        └── necessities.txt

Step 1 – Create your Flask app

In a brand new listing, create the next information:

app.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_geek():
  return '<h1>Good day world!</h2>'

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

necessities.txt

Flask==2.1.1

Step 2 – Create your Docker file

In the identical listing, create a Dockerfile:

Dockerfile

FROM python:3.8-slim-buster

WORKDIR /python-docker

COPY necessities.txt necessities.txt
RUN pip3 set up -r necessities.txt

COPY . .

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

If you wish to go setting variables to your operating docker container, then probably use the next as a substitute:

FROM python:3.8-slim-buster

WORKDIR /python-docker

COPY necessities.txt necessities.txt
RUN pip3 set up -r necessities.txt

COPY . .

ENTRYPOINT ["python3"]

CMD ["app.py"]

Step 3 – Construct your Docker picture

Construct your Docker picture:

docker construct -t ourflaskapp:newest .

Step 4 – Run your Docker container

Run your new Docker container:

sudo docker run -p 5000:5000 ourflaskapp

Leave a Reply