Nginx如何实现动态负载均衡
什么是动态负载均衡
一般情况下,使用nginx搭建的服务器集群,每次修改nginx.conf配置文件都需要重启nginx服务器。动态负载均衡就是修改nginx.conf配置文件后不必重启nginx而使配置生效。
具体实现说明
搭建Nginx+Consul+Upsycn环境。Nginx实现负载均衡和反向代理。Consul是一个开源的注册中心和服务发现的框架。其在Nginx中的动态负载均衡的作用是通过Http api注册和发现服务。Upsycn是新浪微博的开源框架,在Nginx中的动态负载均衡的作用是Consul的后端的server列表,既获得Nginx的上游服务器(Upstream server)信息,并动态的安装更新Nginx的路由信息。
下载安装
- 安装Nginx
wget http://nginx.org/download/nginx-1.15.12.tar.gz
作用:实现反向代理、负载负载库 - 安装consul
wget https://releases.hashicorp.com/consul/1.3.0/consul_1.3.0_linux_amd64.zip
作用:对动态负载均衡均配置实现注册 - 安装nginx-upsync-module
wget https://github.com/weibocom/nginx-upsync-module/archive/master.zip
作用:nginx动态获取最新upstream信息
解压安装
unzip master.zip
unzip consul_0.7.1_linux_amd64.zip
如果解压出现该错误
-bash: unzip: 未找到命令
解决办法
yum -y install unzip
安装Nginx
解压Nginx
tar -zxvf nginx-1.15.12.tar.gz
配置Nginx
groupadd nginx
useradd -g nginx -s /sbin/nologin nginx
mkdir -p /var/tmp/nginx/client/
mkdir -p /usr/local/nginx
编译Nginx
cd nginx-1.15.12
./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
编译的是报错
./configure: error: SSL modules require the OpenSSL library.
解决办法
yum -y install openssl openssl-devel
Upstream 动态配置
##动态去consul 获取注册的真实反向代理地址
upstream aaa{
server 127.0.0.1:11111;
upsync 192.168.212.134:8500/v1/kv/upstreams/itmayiedu upsync_timeout=6m upsync_interval=500ms upsync_type=consul strong_dependency=off;