实现需求linux
用nginx作负载均衡,手动的方式是在upstream中添加或删除后端服务器,比较麻烦.nginx
经过Registrator收集须要注册到Consul做为Nginx后端服务器信息而后注册到Consul key/value.Consul-template去Consul key/value中读取信息,而后自动修改Nginx配置文件并平滑重启Nginx.不须要修改nginx.confweb
环境redis
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 |
步骤docker
mesosphere和Nginx搭建过程省略bootstrap
启动Consul-servervim
[root@slave-1 ~]# docker run -d --name=consul --net=host gliderlabs/consul-server -bootstrap -bind=192.168.0.149
启动Registrator后端
NOTE:这种启动方式是注册到Consul的key/value服务器
[root@slave-1 ~]# docker run -d --name=registrator --net=host --volume=/var/run/docker.sock:/tmp/docker.sock gliderlabs/registrator:latest consulkv://localhost:8500/hello
测试Registrator是否把本机容器注册到Consul key/valueapp
1.启动一个redis容器
[root@slave-1 ~]# docker run -d -P --name=redis redis
2.进入Consul UI界面查看
安装Consul-template
[root@slave-1 ~]# wget -c https://releases.hashicorp.com/consul-template/0.12.0/consul-template_0.12.0_linux_amd64.zip [root@slave-1 ~]# unzip -d . consul-template_0.12.0_linux_amd64.zip [root@slave-1 ~]# cp consul-template /usr/local/bin/.
配置nginx.conf模板
NOTE:
consul-template和nginx必须装到一台机器,由于consul-template须要动态修改nginx配置文件
只须要把nginx.conf默认配置复制到/root/nginx_web.ctmpl,而后修改upstream段.
[root@slave-1 ~]# 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
[root@slave-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