Scale your Flask Python Web Application with Docker and HAProxy

Fri 24 June 2016

For the last few months I was using Docker quite intensively for my projects and I really like it. In this post I will just describe the necessary steps to deploy a minimal Flask python application and scale it using docker-compose and HAProxy.

So, here is a diagram with what I plan to deploy.

I am using a Vultr compute instance with Docker on CentOS 7. After the instance is up and running let's test if docker is working:

# docker run hello-world

it seems that is working, so let's install docker-compose

# yum install python-pip
# pip install docker-compose

if we try to run "docker-compose" command will give us an error

we need to install one more python module to have everything working

# pip install --upgrade backports.ssl_match_hostname

test the installation by running a simple hello world using docker-compose. We have to build a docker-compose.yml file with the following content:

my-test:
image: hello-world

let's bring the container up and running

# docker-compose up

good, working perfectly. Time to prepare the files for our flask python application and haproxy.

Dockerfile - the file is needed to pull a minimal Flask application from my GitHub repository and run it as a docker container

yupiiiii, working. But wait, we have only one service corresponding to our python application. Let's scale our python application (e.g. run 5 instances)

# docker-compose scale pyapp=5

let's check if indeed we have 5 containers for our python app and one container for our load balancer

# docker-compose ps

yes, we have all services as we expected. But there is one more thing to do. After we scaled our python application we need to inform HAProxy about the new containers. You can do that in different ways but I did it like this:

now we can test to see if HAProxy is distributing the requests in Round-Robin mode. I used curl for that but of course you can use your browser as well and refresh the page to see that the hostname change which means that our python application is running in a different container.

that's all. Was not difficult but indeed this is just a minimal application without even a database. Perhaps in a following post I will describe how to build a more complete infrastructure using docker-compose