Deploy ML Model with Flask and Docker
Overview
In this tutorial, we will deploy a pre-trained model by first create a visual web interface using Flask web framework, and then containerize with Docker. Docker will “package up code and all its dependencies so the application runs quickly and reliably from one computing environment to another”. The containerized application can be deployed on hosting platforms like Heroku, or other hosts of your choice.
Prerequisite
- Install Docker (link).
- Have a pre-trained model. You can find an example here, along with all the files mentioned in this tutorial.
The file structure looks like this:
1 | ├── Dockerfile |
Create Flask app
Flask is a popular micro web framework written in Python. In this part, we will create a file app.py
:
1 | import numpy as np |
This app requests a number as input, and predicts a value using my_model.pkl
. You will also need this HTML file to beautify the page.
Specify dependencies
Put the packages required in requirements.txt
:
1 | flask |
Create a Dockerfile
Create a Dockerfile
:
1 | FROM python:3.6-slim-stretch |
This Dockerfile does four things:
- Create a layer from the
python:3.6-slim-stretch
Docker image. You can browse other docker official python images here. - Add the
requirements.txt
file and install all dependencies on top of the basic docker layer. - Add all other files and specify the work directory.
- Specify port and run the app.
Run with Docker
First, build a docker image (you can choose a different tag name)docker build -t flask_app .
Confirm the image is theredocker image ls
Then run the app in a foreground modedocker run -it --rm -p 5000:5000 flask_app
Check http://localhost:5000 to see if the webpage is loaded.
Next steps
We have created a simple flask app to host a pre-trained model, and use Docker to deploy on localhost. From now on we could extend this to all kinds of things. Here are several examples:
- Use more sophisticated pre-trained models to solve tasks like image classification (example) or language recognition.
- Automate the process to generate Dockerfile (example).
- Host app on platforms like Heroku. I have a post previously on hosting a dash app on Heroku. Heroku also supports deploying with Docker.
Some useful docker commands
1 | docker build -t <tag-name> . # create docker image |