Docker Swarm Load Balancer
One of the key feature from Docker Swarm Mode is load balancing.
Demonstration
Precondition, you're running this on a manager node (when running this on your machine, simple run
docker swarm init
)
Given this simple Dockerfile
FROM alpine:3.6
RUN echo "red" > /index.html
EXPOSE 80
ENTRYPOINT busybox httpd -p 80 -h / && tail -f /dev/null
and build it as demo: docker build -t demo .
Now we create a new Docker overlay network named dev
for this demonstration.
docker network create -d overlay --attachable dev
It's important to make it attachable, so we can demonstrate all features from docker swarm load balancing.
- round robin load balancing
- resolving names
We can start now our demo service
docker service create \
--network dev \
--name demo \
demo
and change the "red" in index.html
to "blue" by attaching the service.
docker exec -ti \
$(docker ps --filter "Name=demo" --format {{.Names}}) \
sed -i 's/red/blue/' /index.html
It's time to scale our demo service
docker service scale demo=2
When both services are running (docker service ls
), we can start our container to testing the DNSRR feature.
docker run -ti --network dev alpine:3.6
We need to install curl
/ # apk --update add curl
And finaly we can request for http://demo
/ # curl http://demo
blue
/ # curl http://demo
red
/ # curl http://demo
blue
/ # curl http://demo
red
As you see, one time the swarm resolver 127.0.0.11
requested our first demo service where we changed the index.html
from "red" to "blue".
The second request resolves for the 2nd demo service which contains the original image we've build at the beginning with "red" in index.html
.
It's such simple to scale (load balance) services with Docker Swarm Mode ;)