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.
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.
We need to set up a basic app and Dockerfile.
Start with creating a new directory; let’s call it
Within the directory create an
app.py file containing the below listing as your basic application:
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:
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.
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,
WORKDIR sets the working directory (all following instructions operate within this directory); you may use
WORKDIR as often as you like
ENTRYPOINT configures the container to run as an executable; only the last
ENTRYPOINT instruction executes
pip installs from
requirements.txt as normal. Since
requirements.txt only references
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.
Now that we have a Dockerfile, let’s verify it builds correctly:
docker build -t flask-tutorial:latest .
After the build completes, we can run the container:
docker run -d -p 5000:5000 flask-tutorial
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.