Docker containers in load balancing

Load Balancing

Load balancing is a technique to distribute load/traffic across servers containing the requested material by the client to improve network efficiency and reducing load across one server. For more information you can go to https://www.nginx.com/resources/glossary/load-balancing/.

Building custom network

To create a load balancer for docker containers we have to launch our containers into custom network

docker network create webnet
# it creates a network named webnet with default driver as bridge 
docker network ls
# to check available networks 

Pulling a custom web server

Now, you have to create a custom image of a web server. I used centos:7. You can simply pull my image as given below:

docker pull mykgod/centos7lb:test
# this command will pull this image by docker hub
docker images
# to check images 

Above web server contains a index.php file which shows IP of that container. So after requesting web server, it should show different IPs.

Launching containers

Now we will launch 2 web servers in our custom network webnet.

docker container run -dit --name web1 --network webnet --network-alias webpage mykgod/centos7lb:test
docker container run -dit --name web2 --network webnet --network-alias webpage mykgod/centos7lb:test
# we are giving different container name but same network alias
docker container run -dit --name client --network webnet mykgod/centos7lb:test
# this is client container which will send request

Note: Here –network-alias is working as a load balancer. Also we have to launch a client container because we cannot connect our host to webnet due to public and private IP concept.

Now checking if our setup is working or not

docker container exec client curl webpage
# run above command multiple times 

You can now see every time you run this command you’ll get different IP as per container. To check IP of a web server container you can run…

docker container exec web1 ifconfig 
docker container exec web2 ifconfig 

Now we can say that containers are in load balancing.

I have also automated this work by ansible-playbook you may take a peek at this Github Repo : https://github.com/mykg/docker-containers-in-loadbalancing

Leave a comment

Design a site like this with WordPress.com
Get started