In this article, we’ll take a look at how to dockerize a Flask application. Flask is a microframework for Python, with a basis in Werkzeug and Jinja 2.
The Docker Hub image
Since Docker Hub doesn’t have an official Flask repository at the time of writing, I’ll explain how to build our own. While you can always use a non-official image, it’s generally recommended to make your own Dockerfile to ensure you know what is in the image. We’ll start off with the base of Ubuntu, but you can use any available distro you prefer.
Setting Up
We need to set up a basic app and Dockerfile.
Our basic app
Start with creating a new directory; let’s call it flask_web
:
1 | mkdir flask_web |
Within the directory create an app.py
file containing the below listing as your basic application:
1 | # flask_web/app.py |
Now, we need to include Flask in our requirements.txt
file, again create a text file with your favourite text editor which should contain the following line:
1 | Flask==0.10.1 |
Flask Dockerfile
We’re starting from Linux instead of using the Python repository as our base, as its more clear in which Python version is being installed (what apt
installs on Ubuntu or Debian, or yum
installs on Red Hat and CentOS). You always have the option to build off the python
image instead.
1 | FROM ubuntu:16.04 |
Let’s go over some of these Docker instructions:
MAINTAINER
sets the Author field of the image (useful when pushing to Docker Hub)&& \
isn’t Docker specific, but tells Linux to run the next command as part of the existing line (instead of using multiple RUN
directives, you can use just one)COPY
copies files from the first parameter (the source .
) to the destination parameter (in this case, /app
)WORKDIR
sets the working directory (all following instructions operate within this directory); you may use WORKDIR
as often as you likeENTRYPOINT
configures the container to run as an executable; only the last ENTRYPOINT
instruction executespip
installs from requirements.txt
as normal. Since requirements.txt
only references Flask 0.1.0
, pip
only installs Flask 0.1.0
. If you are using Flask for your app, then you’re likely to have more modules specificed for installation.
Build the image
Now that we have a Dockerfile, let’s verify it builds correctly:
1 | docker build -t flask-tutorial:latest . |
After the build completes, we can run the container:
1 | docker run -d -p 5000:5000 flask-tutorial |
Further information
Ensure you are using the right ports. Flask by default runs on port 5000 (not 8000 like Django or 80 like Apache). Check out Binding Docker Ports for more information.