您的位置:首页 > 运维架构 > Nginx

Consul+Registrator+Consul-template实现动态修改nginx配置文件

2016-04-27 18:09 1006 查看
实现需求
用nginx做负载均衡,手动的方式是在upstream中添加或删除后端服务器,比较麻烦.
通过Registrator收集需要注册到Consul作为Nginx后端服务器信息然后注册到Consul key/value.Consul-template去Consul key/value中读取信息,然后自动修改Nginx配置文件并平滑重启Nginx.不需要修改nginx.conf
环境
192.168.0.149Mesos-masterZookeeperConsul-serverConsul-templateNginx
192.168.0.161Mesos-masterZookeeperMarathon
192.168.0.174Mesos-masterZookeeper
192.168.0.239Mesos-salveRegistrator
步骤
mesosphere和Nginx搭建过程省略
启动Consul-server
[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/value
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息