Load Balancing for Docker Containers with HA Proxy
Load balancing is important for many applications. A popular open source load balancer is HAProxy. Here’s how I used an HAProxy container to automatically discover and load balance a simple web application.
Simple Load Balancing
In an earlier post I created a Simple Load Balanced Application with Docker. This used an HAProxy container available in Docker Hub. In sumamry what was needed was:
The problem with this approach is that you can’t add new web containers without restarting the proxy container. Not a huge problem but it would be nice if the proxy auto-discovered these containers and removed them when they went offline.
Dynamically Configured HA Proxy Container
In order to build a proxy that could automatically included or removed web continares as thaey came and went I used another container that can be found in Docker Hub, eeacms/haproxy. This container includes some scripts that automatically configure HAProxy to load balance across available http servers.
In order to test this I used the same demo application as in the earlier post - a simple PHP web front-end and a Java back-end. In order to more easily test the scaling up and down of the application I also took the opportunity to write a Docker Compose file for the application, which looks like this:
No we can start the application with:
Visiting http://localhost will show you that the application is working. Refreshing the page will result in the same hostname every time since there is currently only one host. Create another two web hosts with the following command:
Now refreshing your browser will result in responses from three different hosts.You can scale the application down to two hosts with:
The eeacms/haproxy container has lots of configuration options, why not take a look.
- Searching for a Cure for Cancer with Docker and Azure
- Readme Files That Are Also Slide Decks
- Create a Simple Swarm Cluster on Azure with ARM
- Getting Started With Docker Swarm on Azure
- Simple Load Balancing for Docker Containers
- Install Docker and Docker Machine
- Mounting Volumes in Boot2Docker on Hyper-V
- Using Docker Machine to create a Docker Host on Azure
- Experiments With Development Using Docker
- Dockerizing a Jekyll Site