實現需求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