Consul+upsync+Nginx 实现动态负载均衡(实战)

一、Consul

Consul是一款开源的分布式服务注册与发现系统,通过HTTP API可以使得服务注册、发现实现起来非常简单。

1.1 环境搭建 

下载:wget https://releases.hashicorp.com/consul/0.7.1/consul_0.7.1_linux_amd64.zip

解压:unzip consul_0.7.1_linux_amd64.zip 

出现以上内容就表示安装成功了!

启动:./consul agent -dev -ui -node=consul-dev -client=192.168.179.129

注意关闭防火墙,浏览器访问端口 8500 出现管理界面(管理负载均衡配置存放信息)搭建完成.

1.2注册Http服务

使用Postman访问,添加信息,存放负载均衡配置

Datacenter指定数据中心,Address指定服务IP,Service.Id指定服务唯一标识,Service.Service指定服务分组,Service.tags指定服务标签(如测试环境、预发环境等),Service.Port指定服务端口。

可以看到这边已经添加上了 

再次添加一个8081端口的服务

 二、nginx-upsync-module

Upsync是新浪微博开源的基于Nginx实现动态配置的三方模块。Nginx-Upsync-Module的功能是拉取Consul的后端server的列表,并动态更新Nginx的路由信息。此模块不依赖于任何第三方模块。Consul作为Nginx的DB,利用Consul的KV服务,每个Nginx Work进程独立的去拉取各个upstream的配置,并更新各自的路由。

1.1安装使用  

安装nginx:wget http://nginx.org/download/nginx-1.9.10.tar.gz 

解压:tar -zxvf nginx-1.9.10.tar.gz

配置:

groupadd nginx

useradd -g nginx -s /sbin/nologin nginx

mkdir -p /var/tmp/nginx/client/

mkdir -p /usr/local/nginx

进入目录 :

cd nginx-1.9.10 

编译Nginx (如报错缺少openssl 执行 yum -y install openssl openssl-devel):

./configure   --prefix=/usr/local/nginx   --user=nginx   --group=nginx   --with-http_ssl_module   --with-http_flv_module   --with-http_stub_status_module   --with-http_gzip_static_module   --with-http_realip_module   --http-client-body-temp-path=/var/tmp/nginx/client/   --http-proxy-temp-path=/var/tmp/nginx/proxy/   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi   --http-scgi-temp-path=/var/tmp/nginx/scgi   --with-pcre --add-module=../nginx-upsync-module-master

make && make install

安装nginx-upsync-module:wget https://github.com/weibocom/nginx-upsync-module/archive/master.zip 解压

1.2Upstream 动态配置:

首先先创建upsync_dump_path:

mkdir /usr/local/nginx/conf/servers/

upsync_dump_path指定从consul拉取的上游服务器后持久化到的位置,这样即使consul服务器出问题了,本地还有一个备份。

upsync指令指定从consul哪个路径拉取上游服务器配置;upsync_timeout配置从consul拉取上游服务器配置的超时时间;upsync_interval配置从consul拉取上游服务器配置的间隔时间;upsync_type指定使用consul配置服务器;strong_dependency配置nginx在启动时是否强制依赖配置服务器,如果配置为on,则拉取配置失败时nginx启动同样失败。upsync_dump_path指定从consul拉取的上游服务器后持久化到的位置,这样即使consul服务器出问题了,本地还有一个备份。

##动态去consul 获取注册的真实反向代理地址

   upstream test{

        server 127.0.0.1:11111;

        upsync 192.168.179.129:8500/v1/kv/upstreams/test upsync_timeout=6m upsync_interval=500ms upsync_type=consul strong_dependency=off;

        upsync_dump_path /usr/local/nginx/conf/servers/servers_test.conf;

    }

 

    server {

        listen       80;

        server_name  localhost;

 

        location / {

            proxy_pass http://test;

            index  index.html index.htm;

        }

    } 

启动nginx

最后再启动consul: 

 ./consul agent -dev -ui -node=consul-dev -client=192.168.179.129

使用postman发送put请求来配置负责均衡:

可以看到,添加了8081和8082端口

好了 配置到这里就结束了,访问nginx发现负载均衡配置完成,现可以很方便的动态配置nginx。

发布了21 篇原创文章 · 获赞 11 · 访问量 4289
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章