|
实现需求
用nginx做负载均衡,手动的方式是在upstream中添加或删除后端服务器,比较麻烦.
通过Registrator收集需要注册到Consul作为Nginx后端服务器信息然后注册到Consul key/value.Consul-template去Consul key/value中读取信息,然后自动修改Nginx配置文件并平滑重启Nginx.不需要修改nginx.conf
环境
192.168.0.149 | Mesos-master | Zookeeper | Consul-server | Consul-template | Nginx | 192.168.0.161 | Mesos-master | Zookeeper | Marathon |
|
| 192.168.0.174 | Mesos-master | Zookeeper |
|
|
| 192.168.0.239 | Mesos-salve | Registrator |
|
|
| 步骤
mesosphere和Nginx搭建过程省略
启动Consul-server
1
| docker run -d --name=consul --net=host gliderlabs/consul-server -bootstrap -bind=192.168.0.149
|
启动Registrator
NOTE:这种启动方式是注册到Consul的key/value
1
| docker run -d --name=registrator --net=host --volume=/var/run/docker.sock:/tmp/docker.sock gliderlabs/registrator:latest consulkv://localhost:8500/hello
|
安装Consul-template
配置nginx.conf模板
NOTE:
consul-template和nginx必须装到一台机器,因为consul-template需要动态修改nginx配置文件
只需要把nginx.conf默认配置复制到这里,然后修改upstream段.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| #vim /root/nginx_web.ctmpl
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream app {
{{range $key, $pairs := tree "hello/" | byKey}}{{range $serverid, $pair := $pairs}}
server {{.Value}}; weight=1 {{end}}{{end}}
}
server {
listen 80;
server_name localhost;
location / {
http://app;
}
}
}
}
|
启动consul-template
1
| consul-template -consul 192.168.0.149:8500 -template /root/nginx_web.ctmpl:/usr/local/nginx/conf/nginx.conf:"/usr/local/nginx/sbin/nginx -s reload"
|
测试:
用marathon启动一个nginx容器,看registrator是否注册到consul,然后看consul-template是否自动添加了这个后端服务器到/usr/local/nginx/conf/nginx.conf
|
|