Dockerize your Flask Application

Dockerize your Flask Application

A simple article to explain how dockerized a Flask App.

In this article, I will show you how was my approach to solve this challenge!

The Flask Architecture and Dependencies

Even though a simple "Hello World" I worked with the best practices of architecture to it. I had the following directory structure:

├── backend
│   ├──
│   ├── blueprints
│   │   ├── core
│   │   │   ├──
│   │   │   ├──
│   │   │   ├──
│   │   │   └── tests
│   │   │       └──
│   │   └──
│   └──
├── Dockerfile
├── .dockerignore
├── .gitignore
├── Pipfile
├── Pipfile.lock
├── pytest.ini

The . (dot) is the root of project. In the backend I have Flask application properly. I used the factory pattern for the architecture. So, in the I have this:

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

    return app

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 backend/bluprints/core I have my blueprint (see de documentation to know more about blueprints), the code is in and, both configure my core blueprint. The first have this code:

from flask import Blueprint

bp = Blueprint('core', __name__)

def config(app):
    from backend.blueprints.core import routes # noqa

And the second has this code:

from backend.blueprints.core.bp import bp

def home():
    return "Hello World"

In the backend/blueprint/core/tests I have my tests of this blueprint. It's a simple test, and its code is:

import pytest

from flask import url_for

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

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

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

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

One is the This file is responsible for set up pytest to run all tests in the application. Its code is:

import pytest

from import create_app

def app():
    app = create_app()
    return app

def client(app):
    with app.test_client() as c:
        yield c

Other is the pytest.ini a simple file that inform to pytest the pattern of the files tests names, in our case the pytest.ini code is:

python_files=test*.py *

Two other files are Pipfile and Pipfile.lock. These files are created or updated by the command pipenv install [package]. As we are going to see later, the most important in our case is the Pipfile.lock because it locks the versions of all dependencies and allows a deterministic installation of these dependencies in our environment.

And we have Dockerfile, 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:

FROM python:3.7.1

LABEL Author="Vicente Marçal"
LABEL E-mail="[email protected]"
LABEL version="0.0.1b"

ENV FLASK_APP "backend/"
ENV FLASK_ENV "development"

RUN mkdir /app

COPY Pip* /app/

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

ADD . /app


CMD flask run --host=

A brief explanaton about it:

FROM python:3.7.1
The `FROM` define the base image that will be used to create my image. In this case, I use the base image of `pyton:3.7.1`.
LABEL Author="Vicente Marçal"
The `LABEL`'s are the way to put some information like the author's name, e-mail to contact and the version of the Dockerfile
RUN mkdir /app
The `RUN` is responsible to execute commands, in this case the `mkdir /app` that create a direcotyr called app into the root.
The `WORKDIR` defines the work directory, in this case my `/app` created previosly in the `RUN` clause.
COPY Pip* /app/
The `COPY` is resposible to copy files from the host to the container, in this case with the `*` inform to Docker to copy all files start whit `Pip` to `/app/`. Pay attention: it is very important to finalize the path of the director with `/`
RUN pip install --upgrade pip && \
    pip install pipenv && \
    pipenv install --dev --system --deploy --ignore-pipfile
This `RUN` clause does the upgrade of `pip`, install `pipenv` and install the Flask App dependencies. To intall Flask dependencies was used `pipenv install` with some flags:
that indicates to install development dependencies, too;
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 `pipenv` exactly this;
`--deploy` with `--ignore-pipfile`
inform `pipenv` to use the `Pipfile.lock` to install all dependencies. In the `Pipfile.lock` we have all dependencies with your versions locked
ADD . /app
After installation of all dependencies with clause `ADD` added all files of the same directory where is Dockerfile on host to `/app` on the container.
In the same directory there is a file called `.dockerignore` that like the `.gitignore` inform Docker to ignore the files and directories in its content.
This clause exposes the port 5000 of the container to the external world.
CMD flask run --host=
Finally, the clause `CMD` execute the commands after build and up the container. In this case, the command is a `flask run --host=` that execute the Flask server in the host and servers our Flask application.
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.

Some words about the use of COPY and ADD:

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 /.

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:

docker build -t vm_docker_flask .

The command docker build will build our image, with the flag -t it put the tag vm_docker_flask in our image and, finally, the last part of the CLI is . (dot) that inform to Docker that the Dockerfile is in the current directory.

This command shows us this result in our terminal:

Sending build context to Docker daemon  29.18kB
Step 1/15 : FROM python:3.7.1
 ---> 1e80caffd59e
Step 2/15 : LABEL Author="Vicente Marçal"
 ---> Running in a7975e93672a
Removing intermediate container a7975e93672a
 ---> 448662ef63d8
Step 3/15 : LABEL E-mail="[email protected]"
 ---> Running in 75f6319066de
Removing intermediate container 75f6319066de
 ---> 0898192a03f7
Step 4/15 : LABEL version="0.0.1b"
 ---> Running in defb5aee2083
Removing intermediate container defb5aee2083
 ---> 02042247ded0
 ---> Running in 5e9124dfa05c
Removing intermediate container 5e9124dfa05c
 ---> c35cd3ecc42f
Step 6/15 : ENV FLASK_APP "backend/"
 ---> Running in ea58e08644ad
Removing intermediate container ea58e08644ad
 ---> f2fb780d29fc
Step 7/15 : ENV FLASK_ENV "development"
 ---> Running in f72976410ba2
Removing intermediate container f72976410ba2
 ---> bb444664e3b0
Step 8/15 : ENV FLASK_DEBUG True
 ---> Running in e18257443538
Removing intermediate container e18257443538
 ---> a2bbca32f540
Step 9/15 : RUN mkdir /app
 ---> Running in ebbcc284fe40
Removing intermediate container ebbcc284fe40
 ---> 7fb8c7fac9f8
Step 10/15 : WORKDIR /app
 ---> Running in c76604d10578
Removing intermediate container c76604d10578
 ---> 074aa15fee4c
Step 11/15 : COPY Pip* /app/
 ---> 554f403d7b11
Step 12/15 : RUN pip install --upgrade pip && pip install pipenv && pipenv install --dev --system --deploy --ignore-pipfile
 ---> Running in 08faec42b7d5
Collecting pip
  Downloading (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 (5.2MB)
Requirement already satisfied: pip>=9.0.1 in /usr/local/lib/python3.7/site-packages (from pipenv) (19.0.3)
Collecting virtualenv-clone>=0.2.5 (from pipenv)
Collecting virtualenv (from pipenv)
  Downloading (2.0MB)
Collecting certifi (from pipenv)
  Downloading (154kB)
Requirement already satisfied: setuptools>=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
 ---> 740ed1329305
Step 13/15 : ADD . /app
 ---> 3551608282e2
Step 14/15 : EXPOSE 5000
 ---> Running in 07b57fe6a5e7
Removing intermediate container 07b57fe6a5e7
 ---> 2e07658bbae8
Step 15/15 : CMD flask run --host=
 ---> Running in bdf7404770f6
Removing intermediate container bdf7404770f6
 ---> cf7d3ee68072
Successfully built cf7d3ee68072
Successfully tagged vm_docker_flask:latest

After that, we need to run our container. The follow Docker CLI command makes the magic:

 docker run -d --name my_container_flask -p 5000:5000 vm_docker_flask

The command docker run runs our container, the flag -d inform to Docker that is running in background, the flag --name put the my_container_flask to our container, the flag -p bind the port 5000 of container to port 5000 of host and, at the end, is the name of our image built in the docker build command.

This command shows us this result in our terminal (or similar, because this command returns the container id):


Now we can do our first test, see if our container is running, for that we execute Docker CLI command like that:

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>5000/tcp   my_container_flask

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 my_container_flask how you can see above.

Another test that we can do is a simple HTTP request. I use httpie application in this test. See the terminal result:

pythonprojects/docker_flask_app [ http         ]
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

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:

 docker exec my_container_flask pytest 

This docker CLI command runs pytest against my_container_flask and if all it is ok we have this terminal result:

=========================== 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/ .                      [100%]

========================= 1 passed in 0.06 seconds =========================

That's all folks!!

I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others. Thank for reading !

docker flask python web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[]( "")**, our full-stack Python development services...

Hire Python Developers India

Looking to build robust, scalable, and dynamic responsive websites and applications in Python? At **[]( "")**, we constantly endeavor to give you exactly what you need. If you need to...

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Hire Web Developer

Looking for an attractive & user-friendly web developer?, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...