Build a Simple Flask APP with Docker




First, let’s learn what exactly Flask is. Flask is a web application framework written in Python. It was developed by Armin Ronacher, who led a team of international Python enthusiasts called Pocco. Flask is based on the Werkzeg WSGI toolkit and the Jinja2 template engine. Both are Pocco projects.

In general, we can deploy a web application in a few lines of python coding without much knowledge of web development.

Hello World!

To create a ‘Hello World!’ application, we can simply write code app.py below:

Python
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

Type python app.py, after seeing these, it means the application is runing on http://127.0.0.1:5000:

And we should see ‘Hello World!’ in the website like this:

Pack the Flask APP Using Docker

Dockerfile
FROM python:3.9
COPY requirements.txt ./
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt
RUN export PYTHONUNBUFFERED=1
WORKDIR /app
COPY app /app/
ENTRYPOINT [ "python", "app.py" ]

Then, we can build the docker image with:

Bash
docker build
     --pull
     --network=host
     --tag flask-demo:latest
     .

Test docker image

NOTE: Flask runs at port 5000 as default.

IMPORTENT: In case you have proxy in you docker setting, remember to change ~/.docker/config.json with:

JSON
{
      "proxies": {
            "default": {
                  "httpProxy": "http://<your-proxy>",
                  "httpsProxy": "http://<your-proxy>",
                  "noProxy": "localhost"
            }
      }
}

After this, you can simply test the docker image with:

Bash
docker run -d --env NO_PROXY="localhost" --network host --name flask-demo flask-demo:latest

Want to build a Gradio APP? See this article.



Leave a Reply

Your email address will not be published. Required fields are marked *