Skip to main content

Dockerize Python Flask Application

 


What is Flask?

Flask is a micro web framework written in Python. It provides you with tools, libraries and technologies that allow you to build a web application. 

To learn more on Flask jump into this official doc.

Flask App

The idea is to create a simple Flask application that exposes multiple rest endpoints and dockerize it.

Directory Structure

We all need is a python file, a requirement file that install the Flask library and a Dockerfile for building image.

├── app.py

├── Dockerfile

└── requirements.txt

$ cat app.py

from flask import Flask
app = Flask(__name__)
@app.route('/')
def webapp():
    return 'Hello world!'

@app.route('/version')
def webapp_version():
    return 'Version: v1'
    
@app.route('/desc')
def webapp_desc():
    return 'A simple web app developed for demo purpose'

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

$ cat requirements.txt

  Flask 

$ cat Dockerfile

FROM python:alpine3.15
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY app.py .
EXPOSE 5000
CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]

Docker build

docker build -t hello-webapp-py .

Docker run

docker run --name py-app -it -p 80:5000 hello-webapp-py

Test

$ curl localhost/
Hello world!

$ curl localhost/version
Version: v1

$ curl localhost/desc
A simple web app developed for demo purpose
 

Comments