The following application demonstrate how to setup a dynamic load balancing with :
- Nginx as a load balancer
- Consul as service registry
- Registrator as service registrator
- Hello World application as sample application
First of all you have to install Consul and Consul UI.
Then you have to start Consul as an agent server on the docker host.
consul agent -server -bootstrap-expect 1 -data-dir /tmp/consul -ui-dir /usr/local/share/consul --client 0.0.0.0
Then you can start the services :
docker-compose up
This should start all services defined in docker-compose.yml
.
The sample app should be running and being available at http://localhost/
, displaying the hostname of the container serving the application.
Now we want to scale up the sample application :
docker-compose scale app=5
and we can see refreshing the sample app in your favorite browser, the hostname should change.
If you check the Consul UI located at http://localhost:8500/ui
, you you should see 5 instances of the sample application (named app).
Now we can scale down the sample application :
docker-compose scale app=1
and the containers should be stopped and destroyed.
The registrator container is responsable for registering and deregistering services based on container start and die events from Docker.
The consul container maintain the service registry.
The nginx use S6 as system init to run nginx and consul-template in the same container.
The role of consul-template is to generate a valid nginx configuration file in /etc/nginx/conf.d
directory based on a template and reload Nginx when new services are registered in Consul.
We would like to thanks :
- Jeff Lindsay for the fantastic work he did for building registrator and consul docker images.
- John Regan for his article on S6 system init which is a great system init.
- Shane Sveller from Tutum for his article on load balancing with Nginx and consul-template which inspired this prototype