Dockerize a Flask App
Tags: docker, flask, python
Published: 2019-10-11 22:54:49

---
title: Dockerize a Flask App
published: true
description: A simple article to explain how dockerized a Flask App
tags: Docker, Flask, Python
---

<a href="http://www.vicentemarcal.com/wp-content/uploads/2019/03/flask-docker.png"><img class="aligncenter size-full wp-image-1054" src="http://www.vicentemarcal.com/wp-content/uploads/2019/03/flask-docker.png" alt="Logomarcas Flask e Docker" width="700" height="300"></a>

Last week I was challenged to start a simple "Hello World" Flask application, but it needed to run into Docker container. In this article, I will show you how was my approach to solve this challenge!
<h1>The Flask Architecture and Dependencies</h1>
Even though a simple "Hello World" I worked with the best practices of architecture to it. I had the following directory structure:
<pre><code>.
├── backend
│   ├── app.py
│   ├── blueprints
│   │   ├── core
│   │   │   ├── bp.py
│   │   │   ├── __init__.py
│   │   │   ├── routes.py
│   │   │   └── tests
│   │   │       └── test_bp_core.py
│   │   └── __init__.py
│   └── __init__.py
├── conftest.py
├── Dockerfile
├── .dockerignore
├── .gitignore
├── Pipfile
├── Pipfile.lock
├── pytest.ini
└── README.md
</code></pre>
The <code>.</code> (dot) is the root of project. In the <code>backend</code> I have Flask application properly. I used the factory pattern for the architecture. So, in the <code>app.py</code> I have this:
<pre><code>from flask import Flask


def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'My_Top_Secert_Key'

    # Blueprint

    from backend.blueprints.core import bp as bp_core
    bp_core.config(app)

    return app
</code></pre>
This code is responsible to create my Flask app. The focus of this article isn't to explain about Flask and so on. But, how to construct an app and run it into a Docker container.

In the <code>backend/bluprints/core</code> I have my blueprint (see de <a href="http://flask.pocoo.org/docs/1.0/blueprints/">documentation to know more about blueprints</a>), the code is in bp.py and route.py, both configure my <strong>core blueprint</strong>. The first have this code:
<pre><code>from flask import Blueprint


bp = Blueprint('core', __name__)


def config(app):
    from backend.blueprints.core import routes # noqa
    app.register_blueprint(bp)
</code></pre>
And the second has this code:
<pre><code>from backend.blueprints.core.bp import bp


@bp.route('/')
def home():
    return "Hello World"
</code></pre>
In the <code>backend/blueprint/core/tests</code> I have my tests of this blueprint. It's a simple test, and its code is:
<pre>import pytest

from flask import url_for


@pytest.fixture
def resp(client):
    return client.get(url_for('core.home'))


def test_bp_home_status_code_ok(resp):
    assert resp.status_code == 200

</pre>
Again, the focus of this article isn't to explain detailed of the Flask application, so if you have questions about how to test Flask apps please see <a href="http://flask.pocoo.org/docs/1.0/testing/">the documentation</a>.

Back to the root of the application, I have some files that are interesting to see!

One is the <code>conftest.py</code>. This file is responsible for set up <code>pytest</code> to run all tests in the application. Its code is:
<pre><code>import pytest

from backend.app import create_app


@pytest.fixture
def app():
    app = create_app()
    return app


@pytest.fixture
def client(app):
    with app.test_client() as c:
        yield c
</code></pre>
Other is the <code>pytest.ini</code> a simple file that inform to <code>pytest</code> the pattern of the files tests names, in our case the <code>pytest.ini</code> code is:
<pre><code>[pytest]
python_files=test*.py *tests.py
</code></pre>
Two other files are <code>Pipfile</code> and <code>Pipfile.lock</code>. These files are created or updated by the command <code>pipenv install [package]</code>. As we are going to see later, the most important in our case is the <code>Pipfile.lock</code> because it locks the versions of all dependencies and allows a deterministic installation of these dependencies in our environment.

And we have <code>Dockerfile</code>, too. This file is responsible for the Docker Image creation. This Image will be used to up the container with the Flask Application. Its code is:
<pre><code>FROM python:3.7.1

LABEL Author="Vicente Marçal"
LABEL E-mail="vicente.marcal@gmail.com"
LABEL version="0.0.1b"

ENV PYTHONDONTWRITEBYTECODE 1
ENV FLASK_APP "backend/app.py"
ENV FLASK_ENV "development"
ENV FLASK_DEBUG True

RUN mkdir /app
WORKDIR /app

COPY Pip* /app/

RUN pip install --upgrade pip &amp;&amp; \
    pip install pipenv &amp;&amp; \
    pipenv install --dev --system --deploy --ignore-pipfile

ADD . /app

EXPOSE 5000

CMD flask run --host=0.0.0.0
</code></pre>
A brief explanaton about it:
<dl>
 	<dt>
<pre><code>FROM python:3.7.1</code></pre>
</dt>
 	<dd>The <code>FROM</code> define the base image that will be used to create my image. In this case, I use the base image of <code>pyton:3.7.1</code>.</dd>
 	<dt>
<pre><code>LABEL Author="Vicente Marçal"</code></pre>
</dt>
 	<dd>The <code>LABEL</code>'s are the way to put some information like the author's name, e-mail to contact and the version of the Dockerfile</dd>
 	<dt>
<pre><code>RUN mkdir /app</code></pre>
</dt>
 	<dd>The <code>RUN</code> is responsible to execute commands, in this case the <code>mkdir /app</code> that create a direcotyr called app into the root.</dd>
 	<dt>
<pre><code>WORKDIR /app</code></pre>
</dt>
 	<dd>The <code>WORKDIR</code> defines the work directory, in this case my <code>/app</code> created previosly in the <code>RUN</code> clause.</dd>
 	<dt>
<pre><code>COPY Pip* /app/</code></pre>
</dt>
 	<dd>The <code>COPY</code> is resposible to copy files from the host to the container, in this case with the <code>*</code> inform to Docker to copy all files start whit <code>Pip</code> to <code>/app/</code>. Pay attention: it is very important to finalize the path of the director with <code>/</code></dd>
 	<dt>
<pre><code>RUN pip install --upgrade pip &amp;&amp; \
&nbsp;&nbsp;&nbsp;&nbsp;pip install pipenv &amp;&amp; \
&nbsp;&nbsp;&nbsp;&nbsp;pipenv install --dev --system --deploy --ignore-pipfile</code></pre>
</dt>
 	<dd>This <code>RUN</code> clause does the upgrade of <code>pip</code>, install <code>pipenv</code> and install the Flask App dependencies. To intall Flask dependencies was used <code>pipenv install</code> with some flags:</dd>
</dl>
<dl>
 	<dt><code>--dev</code></dt>
 	<dd>that indicates to install development dependencies, too;</dd>
 	<dt><code>--system</code></dt>
 	<dd>this is very important because in a Docker container we have an isolated environment yet and it is not necessary create a virtualenv, this flag informs <code>pipenv</code> exactly this;</dd>
 	<dt><code>--deploy</code> with <code>--ignore-pipfile</code></dt>
 	<dd>inform <code>pipenv</code> to use the <code>Pipfile.lock</code> to install all dependencies. In the <code>Pipfile.lock</code> we have all dependencies with your versions locked</dd>
</dl>
<dl>
 	<dt>
<pre><code>ADD . /app</code></pre>
</dt>
 	<dd>After installation of all dependencies with clause <code>ADD</code> added all files of the same directory where is Dockerfile on host to <code>/app</code> on the container.</dd>
</dl>
<dl>
 	<dt>Obs:</dt>
 	<dd>In the same directory there is a file called <code>.dockerignore</code> that like the <code>.gitignore</code> inform Docker to ignore the files and directories in its content.</dd>
</dl>
<dl>
 	<dt>
<pre><code>EXPOSE 5000</code></pre>
</dt>
 	<dd>This clause exposes the port 5000 of the container to the external world.</dd>
 	<dt>
<pre><code>CMD flask run --host=0.0.0.0</code></pre>
</dt>
 	<dd>Finally, the clause <code>CMD</code> execute the commands after build and up the container. In this case, the command is a <code>flask run --host=0.0.0.0</code> that execute the Flask server in the host 0.0.0.0 and servers our Flask application.</dd>
</dl>
<dl>
 	<dt>Obs:</dt>
 	<dd>Obviously, this is a small test. If you need to use this in production it is recommended to run a WSGI server like a uWSGI or gunicorn instead the Flask Server that is used only in development environment.</dd>
</dl>
Some words about the use of <code>COPY</code> and <code>ADD</code>:
<blockquote cite="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/">Although ADD and COPY are functionally similar, generally speaking, COPY is preferred. That’s because it’s more transparent than ADD. COPY only supports the basic copying of local files into the container, while ADD has some features (like local-only tar extraction and remote URL support) that are not immediately obvious. Consequently, the best use for ADD is local tar file auto-extraction into the image, as in ADD rootfs.tar.xz /.</blockquote>
Ref.: <a href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/">https://docs.docker.com/develop/develop-images/dockerfile_best-practices/</a>

That's all we need to Dockerize our Flask App. Now we need to build and run our Docker image.

To build we use this Docker CLI command:
<pre><code>docker build -t vm_docker_flask .
</code></pre>
The command <code>docker build</code> will build our image, with the flag <code>-t</code> it put the tag <strong>vm_docker_flask</strong> in our image and, finally, the last part of the CLI is <code>.</code> (dot) that inform to Docker that the Dockerfile is in the current directory.

This command shows us this result in our terminal:
<pre><code>Sending build context to Docker daemon  29.18kB
Step 1/15 : FROM python:3.7.1
 ---&gt; 1e80caffd59e
Step 2/15 : LABEL Author="Vicente Marçal"
 ---&gt; Running in a7975e93672a
Removing intermediate container a7975e93672a
 ---&gt; 448662ef63d8
Step 3/15 : LABEL E-mail="vicente.marcal@gmail.com"
 ---&gt; Running in 75f6319066de
Removing intermediate container 75f6319066de
 ---&gt; 0898192a03f7
Step 4/15 : LABEL version="0.0.1b"
 ---&gt; Running in defb5aee2083
Removing intermediate container defb5aee2083
 ---&gt; 02042247ded0
Step 5/15 : ENV PYTHONDONTWRITEBYTECODE 1
 ---&gt; Running in 5e9124dfa05c
Removing intermediate container 5e9124dfa05c
 ---&gt; c35cd3ecc42f
Step 6/15 : ENV FLASK_APP "backend/app.py"
 ---&gt; Running in ea58e08644ad
Removing intermediate container ea58e08644ad
 ---&gt; f2fb780d29fc
Step 7/15 : ENV FLASK_ENV "development"
 ---&gt; Running in f72976410ba2
Removing intermediate container f72976410ba2
 ---&gt; bb444664e3b0
Step 8/15 : ENV FLASK_DEBUG True
 ---&gt; Running in e18257443538
Removing intermediate container e18257443538
 ---&gt; a2bbca32f540
Step 9/15 : RUN mkdir /app
 ---&gt; Running in ebbcc284fe40
Removing intermediate container ebbcc284fe40
 ---&gt; 7fb8c7fac9f8
Step 10/15 : WORKDIR /app
 ---&gt; Running in c76604d10578
Removing intermediate container c76604d10578
 ---&gt; 074aa15fee4c
Step 11/15 : COPY Pip* /app/
 ---&gt; 554f403d7b11
Step 12/15 : RUN pip install --upgrade pip &amp;&amp; pip install pipenv &amp;&amp; pipenv install --dev --system --deploy --ignore-pipfile
 ---&gt; Running in 08faec42b7d5
Collecting pip
  Downloading https://files.pythonhosted.org/packages/d8/f3/413bab4ff08e1fc4828dfc59996d721917df8e8583ea85385d51125dceff/pip-19.0.3-py2.py3-none-any.whl (1.4MB)
Installing collected packages: pip
  Found existing installation: pip 18.1
    Uninstalling pip-18.1:
      Successfully uninstalled pip-18.1
Successfully installed pip-19.0.3
Collecting pipenv
  Downloading https://files.pythonhosted.org/packages/13/b4/3ffa55f77161cff9a5220f162670f7c5eb00df52e00939e203f601b0f579/pipenv-2018.11.26-py3-none-any.whl (5.2MB)
Requirement already satisfied: pip&gt;=9.0.1 in /usr/local/lib/python3.7/site-packages (from pipenv) (19.0.3)
Collecting virtualenv-clone&gt;=0.2.5 (from pipenv)
  Downloading https://files.pythonhosted.org/packages/e3/d9/d9c56deb483c4d3289a00b12046e41428be64e8236fa210111a1f57cc42d/virtualenv_clone-0.5.1-py2.py3-none-any.whl
Collecting virtualenv (from pipenv)
  Downloading https://files.pythonhosted.org/packages/33/5d/314c760d4204f64e4a968275182b7751bd5c3249094757b39ba987dcfb5a/virtualenv-16.4.3-py2.py3-none-any.whl (2.0MB)
Collecting certifi (from pipenv)
  Downloading https://files.pythonhosted.org/packages/9f/e0/accfc1b56b57e9750eba272e24c4dddeac86852c2bebd1236674d7887e8a/certifi-2018.11.29-py2.py3-none-any.whl (154kB)
Requirement already satisfied: setuptools&gt;=36.2.1 in /usr/local/lib/python3.7/site-packages (from pipenv) (40.6.2)
Installing collected packages: virtualenv-clone, virtualenv, certifi, pipenv
Successfully installed certifi-2018.11.29 pipenv-2018.11.26 virtualenv-16.4.3 virtualenv-clone-0.5.1
Installing dependencies from Pipfile.lock (9a5a3a)…
Removing intermediate container 08faec42b7d5
 ---&gt; 740ed1329305
Step 13/15 : ADD . /app
 ---&gt; 3551608282e2
Step 14/15 : EXPOSE 5000
 ---&gt; Running in 07b57fe6a5e7
Removing intermediate container 07b57fe6a5e7
 ---&gt; 2e07658bbae8
Step 15/15 : CMD flask run --host=0.0.0.0
 ---&gt; Running in bdf7404770f6
Removing intermediate container bdf7404770f6
 ---&gt; cf7d3ee68072
Successfully built cf7d3ee68072
Successfully tagged vm_docker_flask:latest
</code></pre>
After that, we need to run our container. The follow Docker CLI command makes the magic:
<pre><code> docker run -d --name my_container_flask -p 5000:5000 vm_docker_flask
</code></pre>
The command <code>docker run</code> runs our container, the flag <code>-d</code> inform to Docker that is running in background, the flag <code>--name</code> put the <strong>my_container_flask</strong> to our container, the flag <code>-p</code> bind the port 5000 of container to port 5000 of host and, at the end, is the name of our image built in the <code>docker build</code> command.

This command shows us this result in our terminal (or similar, because this command returns the container id):
<pre><code>33169f573b7bdf078ef8d55741ec037f2914aa78343ad96c8277854c3bcdf6b2
</code></pre>
Now we can do our first test, see if our container is running, for that we execute Docker CLI command like that:
<pre><code>pythonprojects/docker_flask_app [ docker container ps        ] 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
880a5b59f2aa        vm_docker_flask     "/bin/sh -c 'flask r…"   15 minutes ago      Up 15 minutes       0.0.0.0:5000-&gt;5000/tcp   my_container_flask
</code></pre>
This Docker CLI command shows us if our which containers are running and their info like Container ID, Image, Command and so on. In our case only <strong>my_container_flask</strong> how you can see above.

Another test that we can do is a simple HTTP request. I use <a href="https://httpie.org/">httpie application</a> in this test. See the terminal result:
<pre><code>pythonprojects/docker_flask_app [ http 0.0.0.0:5000         ]
HTTP/1.0 200 OK
Content-Length: 11
Content-Type: text/html; charset=utf-8
Date: Tue, 05 Mar 2019 18:17:24 GMT
Server: Werkzeug/0.14.1 Python/3.7.1

Hello World
</code></pre>
Now the most important test. We execute the pytest into our container to run tests against our Flask application. The test is just simple only assert if the status code returned by the Flask App is 200 Ok!

To do it we execute the follow Docker CLI command:
<pre><code> docker exec my_container_flask pytest 
</code></pre>
This docker CLI command runs pytest against my_container_flask and if all it is ok we have this terminal result:
<pre><code>=========================== test session starts ============================
platform linux -- Python 3.7.1, pytest-4.3.0, py-1.8.0, pluggy-0.9.0
rootdir: /app, inifile: pytest.ini
plugins: sugar-0.9.2, flask-0.14.0
collected 1 item

backend/blueprints/core/tests/test_bp_core.py .                      [100%]

========================= 1 passed in 0.06 seconds =========================
</code></pre>
<h2>That's all folks!!</h2>