Back to blog
Jul 02, 2024
3 min read

Building Load Balancing and High Availability Application with Docker Swarm

Talking about how to use Docker Swarm to build Load Balancing Application.

Intro Docker Swarms

Docker Swarm is a native clustering and orchestration tool for Docker containers. Docker Swarm allows you to manage a cluster of Docker hosts as a single virtual system. It consists of manager nodes (which handle cluster management) and worker nodes (which run containers) Comparison the feature-rich Kubernetes,Docker Swarm is often considered easier to learn and use for smaller-scale deployments.

Key features:

  • Cluster management integrated with Docker Engine
  • Decentralized design
  • Declarative service model
  • Scaling
  • Load balancing
  • Service discovery
  • Rolling updates

Functionality:

  • Deploys containers across multiple hosts
  • Manages services and tasks
  • Ensures high availability and fault tolerance
  • Provides built-in load balancing

Steps for using Docker Swarms

I have installed two VM:

  • debian26, which IP Address is 172.16.167.129
  • fedora26, which IP Address is 172.16.167.128

I will let debian26 running as a manager, and fedora26 running as a worker.

At first, I will run docker swarm init command at debian26: img01

docker ps
docker service ls

img02

docker service ps friendlyhello_web

img03

Now, go to fedora26 run this command:

docker swarm join --token SWMTKN-1-5q0j5ph88zixc88myjcajjzaruoo6nn7duqbfywg2vf02i1gay-51u7wukcpcjixnc7aq4b8g11y 172.16.167.129:2377

img04

when you run these command such as:

docker service ps friendlyhello_web
docker service ls

you will get error message.

img05

Then you run this command docker stack deploy -c docker-compose.yml friendlyhello you will get this message.

img06

Before I have run docker stack deploy -c docker-compose.yml friendlyhello, it just only have 5 replicas. Now I change docker-compose.yml file, lets run 12 replicas, then redo this command.

The steps will be:

nano docker-compose.yml
docker stack deploy -c docker-compose.yml friendlyhello

docker service ls
docker service ps friendlyhello_web

I can find it is running 12 replicas services and distributed to fedora26 and debian26 VM.

img07

I go back to fedora26 VM, then run docker ps command, I can get this interface.

img08

Then I go to Debian26 VM , run this command:

img09

docker service scale friendlyhello_web=20

then run this command at Debian26 VM:

docker service ps friendlyhello_web

img10

We can see that the friendlyhello service has been scaled out to 20 nodes and distributed to two VMs, each of which can run 10 nodes.

How to test it

At Debian26 VM, I open web browser to visit http://localhost:4000/ I got this interface.

img11

img12

I go back to Fedora26 VM, run “docker container ls” command, I can find the special number for the node.

img13

At Fedora26 VM, I open web browser to visit http://localhost:4000/ I got this interface.

img14

img15