If
you check the Consul UI, you will see that the two containers are properly regis‐
tered, thanks to
registrator
, as shown in
Figure 10-4
.
Figure 10-4. Consul dynamic load-balancing nodes
Create an Nginx configuration file that acts as a load-balancer for these two applica‐
tions. Assuming your Docker host is
192.168.33.10
, the following example will
work:
events {
worker_connections 1024;
}
http {
upstream elb {
server 192.168.33.10:5001;
server 192.168.33.10:5002;
}
server {
listen 80;
location / {
proxy_pass http://elb;
}
310 | Chapter 10: Application Use Cases
}
}
Next start your Nginx container, binding port 80 of the container to port 80 of the
host, and mount your configuration file inside the container.
Give your container a
name that will prove handy later:
$ docker run -d -p 80:80 -v /home/vagrant/nginx.conf:/etc/nginx/nginx.conf
--name elb nginx
At this stage, you have a basic load-balancing setup.
The Nginx container exposes
port 80 on the host, and load balances two application containers. If you use
curl
to
send an HTTP request
to your Nginx container, you will get the container ID of the
two application containers. It will look like this:
$ curl http://192.168.33.10
8eaab9c31e1a
$ curl http://192.168.33.10
a970ec6274ca
$ curl http://192.168.33.10
8eaab9c31e1a
$ curl http://192.168.33.10
a970ec6274ca
Up to now, there is nothing dynamic except the registration of the containers. To be
able to reconfigure Nginx when containers come and go,
you need a system that will
watch keys in Consul and write a new Nginx configuration file when the values
change. That is where
confd
comes into play.
Download a
confd
binary from the Git‐
Hub release
page
.
The quick start
guide
is good. But we will go over the basic steps. First let’s
create the
directories that will hold your configuration templates:
sudo mkdir -p /etc/confd/{conf.d,templates}
Next create a resource template,
resource config
. This file basically tells
confd
where
the configuration template is that you want to be managed
and tells where to write
the configuration file after the values have been replaced. In
/etc/confd/conf.d/
config.toml
write:
[template]
src = "config.conf.tmpl"
dest = "/home/vagrant/nginx.conf"
keys = [
"/elb/hostname",
]
Now let’s write our Nginx template file in
/etc/confd/templates/config.conf.tmpl
. These
templates are Golang text
templates
, so anything that you can do in a Golang tem‐
plate, you can do in this template:
Do'stlaringiz bilan baham: