Nginx动态配置负载均衡(Consul+upsync+Nginx)

1.常用的动态配置Nginx负载均衡方式

  1. Consul+Consul-template 每次发现配置更改,重启Nginx。
  2. Consul+OpenResty 实现无需重启Nginx的动态负载均衡。
  3. Consul+upsync+Nginx 实现无需重启Nginx的动态负载均衡。

(本文如果有错别字还请大家提醒一下)

2、配置Concul服务器

2.1安装解压ZIP软件

如果未安装 unzip软件,在解压ZIP包的时候会提示未找到unzip该命令
yum -y install unzip

2.2、目前consul官网最新版本为1.6.0

https://www.consul.io/downloads.html

2.3、进入你需要存放下载文件的文件夹,没有的话可以自己创建

cd /home/program

2.4、开始下载concul1.6.0

wget https://releases.hashicorp.com/consul/1.6.0/consul_1.6.0_linux_amd64.zip

2.5、解压concul.zip

unzip consul_1.6.0_linux_amd64.zip
解压后是一个安装文件(绿色字体的文件为安装文件)

2.6、将原先在/home/program的consul文件复制到/usr/local

因为我为了启动一系列的插件方便所以将这个文件复制到了/usr/local

2.7、安装concul

./consul
出现以下文字说明安装成功

Usage: consul [--version] [--help] <command> [<args>]

Available commands are:
    acl            Interact with Consul's ACLs
    agent          Runs a Consul agent
    catalog        Interact with the catalog
    config         Interact with Consul's Centralized Configurations
    connect        Interact with Consul Connect
    debug          Records a debugging archive for operators
    event          Fire a new event
    exec           Executes a command on Consul nodes
    force-leave    Forces a member of the cluster to enter the "left" state
    info           Provides debugging information for operators.
    intention      Interact with Connect service intentions
    join           Tell Consul agent to join cluster
    keygen         Generates a new encryption key
    keyring        Manages gossip layer encryption keys
    kv             Interact with the key-value store
    leave          Gracefully leaves the Consul cluster and shuts down
    lock           Execute a command holding a lock
    login          Login to Consul using an auth method
    logout         Destroy a Consul token created with login
    maint          Controls node or service maintenance mode
    members        Lists the members of a Consul cluster
    monitor        Stream logs from a Consul agent
    operator       Provides cluster-level tools for Consul operators
    reload         Triggers the agent to reload configuration files
    rtt            Estimates network round trip time between nodes
    services       Interact with services
    snapshot       Saves, restores and inspects snapshots of Consul server state
    tls            Builtin helpers for creating CAs and certificates
    validate       Validate config files/directories
    version        Prints the Consul version
    watch          Watch for changes in Consul

或者使用 ./consul version也可以查询是否安装成功
下面为查询后的消息
Consul v1.6.0
Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use protocol >2 when speaking to compatible agents)

2.8、查询本机的IP地址

ip add

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:50:56:2e:45:ee brd ff:ff:ff:ff:ff:ff
    inet 192.168.114.137/24 brd 192.168.114.255 scope global noprefixroute dynamic ens33
       valid_lft 1393sec preferred_lft 1393sec
    inet6 fe80::faea:9a76:9413:c38f/64 scope link tentative noprefixroute dadfailed 
       valid_lft forever preferred_lft forever
    inet6 fe80::4443:cd02:94ff:2ff8/64 scope link tentative noprefixroute dadfailed 
       valid_lft forever preferred_lft forever
    inet6 fe80::c11d:2dbb:747:d77b/64 scope link tentative noprefixroute dadfailed 
       valid_lft forever preferred_lft forever

我的IP地址为192.168.114.137

2.9、启动consul

关闭防火墙
systemctl disable firewalld
移动当前目录至 /usr/local
cd /usr/local
启动consul命令(-client=本机电脑的IP)
./consul agent -server -dev -ui -node=consul-dev -client=192.168.114.137

2.10、打开浏览器查看consul

http://192.168.114.137:8500/ui

2.11、通过POST请求设定配置参数

访问地址
http://192.168.114.137:8500/v1/catalog/register
JSON格式
{“Datacenter”: “dc1”, “Node”:“tomcat”, “Address”:“192.168.114.137”,“Service”: {“Id” :“one”, “Service”: “demoserver_1”,“tags”: [“dev”], “Port”: 80}}

Datacenter:指定数据中心
Address:指定服务IP(现在就是指向自己也就是本机consul地址)
Service.Id:指定服务唯一标识(可以改成其他字符,但是必须唯一)
Service.Service:指定服务分组
Service.tags:指定服务标签(如测试环境、预发环境等)
Service.Port:指定服务端口。

2.12、关闭consul

consul leave -rpc-addr=192.168.114.137:8500

2.13、consul创建模块的相关问题说明

若果你的consul服务可以访问,那么请添加server模块
我这里使用POSTMAN来添加的 传递使用PUT不是为POST
如果consul不能访问,错误为如下

==> Starting Consul agent...
           Version: 'v1.6.0'
           Node ID: 'c8789f1a-4b2c-b016-a1f2-76620a91d1a9'
         Node name: 'consul-dev'
        Datacenter: 'dc1' (Segment: '<all>')
            Server: true (Bootstrap: false)
       Client Addr: [192.168.114.130] (HTTP: 8500, HTTPS: -1, gRPC: 8502, DNS: 8600)
      Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
           Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false, Auto-Encrypt-TLS: false

==> Log data will now stream in as it occurs:

    2019/08/27 19:06:28 [DEBUG] agent: Using random ID "c8789f1a-4b2c-b016-a1f2-76620a91d1a9" as node ID
    2019/08/27 19:06:28 [DEBUG] tlsutil: Update with version 1
    2019/08/27 19:06:28 [INFO] consul: shutting down server
==> Error starting agent: Failed to start Consul server: Failed to start RPC layer: listen tcp 127.0.0.1:8300: bind: address already in use
    2019/08/27 19:06:28 [INFO] agent: Exit code: 1

原因:consul已被启动
解决办法 杀死consul进程
ps -ef|grep consul 寻找consul进程
root 7343 7153 0 14:42 pts/0 00:00:14 ./consul agent -dev -ui -node=consul-dev -client=192.168.114.130
root 47021 7153 0 19:12 pts/0 00:00:00 grep --color=auto consul
kill -9 7343 这个7343就为consul的进程ID 这样就可以重新启动consul了

2.14、删除consul的节点或者服务

1.6的版本通过API接口删除,无法实现,因为无法从页面获取它的节点ID 或者服务ID(实测如此,很重要,请记住)
下面是搜到的方法
Datacenter 与你所创建的Datacenter 相关配置名称一致
Node 与你创建的Node服务一致

curl -X PUT -H ‘application/json’ -d ‘{“Datacenter”: “dc1”,“Node”: “tomcat”}’ http://192.168.114.137:8500/v1/catalog/deregister

删除后记得重启consul服务端,不然你会发现你删除的节点还会回来的
注销服务 尽量别用API吧 尽量使用客户端上的conusl.d来进行服务注册和注销
原文连接:https://my.oschina.net/jastme/blog/1929106

3、配置Nginx服务器

3.1完全卸载Nginx服务器

rm -rf file /usr/local/nginx* (这里指向的是你的Nginx的安装位置)

3.2、开始安装相关插件

安装gcc gcc-c++(新环境安装)
yum install -y gcc gcc-c++
安装下载工具WGET(新环境安装)
yum -y install wget
安装PCRE库(新环境安装)
yum -y install pcre-devel
安装Perl 5(新环境安装)
如果没有安装Perl 5就会在安装SSL的时候提示需要安装
yum install -y pcre pcre-devel
安装SSL库(新环境安装)
yum -y install openssl openssl-devel
安装zlib库(新环境安装)
yum install -y zlib zlib-devel
安装unzip插件(新环境安装)
yum -y install unzip
安装防火墙插件firewalld(新环境安装)
yum install firewalld firewall-config
相关命令
启动:# systemctl start firewalld
查看状态:# systemctl status firewalld 或者 firewall-cmd --state
停止:# systemctl disable firewalld
禁用:# systemctl stop firewalld

3.3下载nginx压缩包与matser压缩包

wget http://nginx.org/download/nginx-1.10.2.tar.gz
wget https://github.com/weibocom/nginx-upsync-module/archive/master.zip

3.4解压nginx压缩包与matser压缩包

tar -zxvf nginx-1.10.2.tar.gz
unzip master.zip
注:master的解压文件一定要与Nginx的解压文件在同一个目录下

3.5配置Nginx相关配置文件

移动当前位置
cd /usr/local/
创建一个新的Nginx组
groupadd nginx
创建用户
useradd -g nginx -s /sbin/nologin nginx
创建目录文件
mkdir -p /var/tmp/nginx/client/
mkdir -p /usr/local/nginx

3.6开始安装Nginx

这个是我解压的地址,你们可以按照你们自己解压的地址来
cd /home/program
进入nginx的文件夹
cd nginx-1.10.2
输入命令重新编译(–add-module指的就是第三方插件)
./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

3.7配置ngxin.conf

移动位置指nginx安装完成的目录
cd /usr/local/nginx
进入配置文件夹
cd conf
对配置文件进行内容修改
vi nginx.conf
具体内容:

#nginx进程数,建议设置为等于CPU总核心数。
worker_processes  1;
#工作模式与连接数上限
events {
    worker_connections  1024;
}

#设定http服务器
http {
        #文件扩展名与文件类型映射表
    include       mime.types;
    #默认文件类型
    default_type  application/octet-stream;
    #默认编码
    #charset utf-8;
    #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,
    #对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,
    #以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改 成off。
    sendfile        on;
    #长连接超时时间,单位是秒
    keepalive_timeout  65;
        #负载均衡地址配置,uspync后面跟的地址为你的consul地址
        upstream serverurl{
        		;##这个地址可以不管他,官方默认固定操作
                server 127.0.0.1:11111
                
                ##upsync:连接consulServer获取动态的upstreams 配置负载均很信息  (需要指定其某个模块服务名,这里指向了demoserver)
                ##upsync_timeout:超时时间6秒(配置从consul拉取上游服务器配置的超时时间)
                ##upsync_interval:每次访问的间隔时间0.5秒*(配置从consul拉取上游服务器配置的间隔时间)
                ##upsync_type:指定使用consul配置服务器
                ##strong_dependency:配置nginx在启动时是否强制依赖配置服务器,如果配置为on,则拉取配置失败时nginx启动同样失败
        		upsync 192.168.114.130:8500/v1/kv/upstreams/demoserver upsync_timeout=6m upsync_interval=500ms upsync_type=consul 		strong_dependency=off;
		        ##动态获取consulServer相关负载均衡配置信息持久化在硬盘
		        upsync_dump_path /usr/local/nginx/conf/servers/servers_test.conf;
}
     #虚拟主机的配置
    server {
                #默认监听端口号
		        listen   80;
		        #设置拦截的域名 http://localhost
		        server_name  localhost;
		       #location 配置反向代理信息
		        location / {
		                 #nginx转发真实服务器地址
		                 proxy_pass  http://serverurl;
		                 index  index.html index.htm;
		        }
    }  
}

3.8、创建配置文件servers_test.conf

由于我们需要动态获取consulServer相关负载均衡配置信息持久化在硬盘,所欲需要创建servers_test.conf,名字可以自己定义但是必须要与配置文件中的文件名称相同
创建文件夹servers
mkdir /usr/local/nginx/conf/servers
移动当前位置
cd /usr/local/nginx/conf/servers
创建配置文件servers_test.conf
touch servers_test.conf

3.9、启动Nginx

移动当前位置
cd /usr/local/nginx/conf/
启动
./nginx
检查是否启动成功
ps -ef | grep nginx
结果一般如下就是启动成功

root 20878 1 0 10:33 ? 00:00:00 nginx: master process ./nginx
nginx 20879 20878 0 10:33 ? 00:00:00 nginx: worker process
root 20882 7425 0 10:35 pts/0 00:00:00 grep --color=auto nginx

4、回到我们的consul

4.1、打开我们的consul管理界面

http://192.168.114.137:8500/ui/dc1/services(这里是我自己所搭建的管理界面,你们IP换一下就好了)

4.2、查看服务

是否已经创建了服务,如果没有创建服务则需要创建服务
通过POSTMAN 发送PUT请求创建,可以查看本文章处的 2.11(CTRL+F搜索直达)

4.3、添加nginx upstream(负载均衡)服务

基于POSTMAN的PUT请求添加
http://192.168.114.137:8500/v1/kv/upstreams/demoserver_1/192.168.114.131:80
http://192.168.114.137:8500/v1/kv/upstreams/demoserver_1/192.168.114.132:80
http://192.168.114.137:8500/v1/kv/upstreams/demoserver_1/192.168.114.133:80
http://192.168.114.137:8500/v1/kv/upstreams/demoserver_1/192.168.114.134:80
http://192.168.114.137:8500/v1/kv/upstreams/demoserver_1/192.168.114.135:80
基于linux命令行添加(必须得在搭建consul的服务器上添加)
curl -X PUT http://192.168.114.137:8500/v1/kv/upstreams/demoserver_1/192.168.114.131:80
curl -X PUT http://192.168.114.137:8500/v1/kv/upstreams/demoserver_1/192.168.114.132:80
curl -X PUT http://192.168.114.137:8500/v1/kv/upstreams/demoserver_1/192.168.114.133:80
curl -X PUT http://192.168.114.137:8500/v1/kv/upstreams/demoserver_1/192.168.114.134:80
curl -X PUT http://192.168.114.137:8500/v1/kv/upstreams/demoserver_1/192.168.114.135:80
注意注意
配置好这些地址后,一定要确认这些服务是否全部启动,如果没有启动你需要去启动,我这里死活跳转不了这些网站,看了以下Nginx错误日志信息,发现原来服务没有启动。把这些服务启动后就全部好了,能够正常按照轮询访问服务器了,当然自己可以设置权重,以及IP绑定。
一些权重等配置可以在consul管理界面去配置
{“weight”:1, “max_fails”:2, “fail_timeout”:10, “down”:0}
weight:权重
max_fails:最大失败访问次数,此时如果发现后端异常,在单位周期为fail_timeout设置的时间,中达到max_fails次数,这个周期次数内,如果后端同一个节点不可用,那么接将把节点标记为不可用,并等待下一个周期(同样时常为fail_timeout)再一次去请求,判断是否连接是否成功。如果成功,将恢复之前的轮询方式,如果不可用将在下一个周期(fail_timeout)再试一次。
fail_timeout:连接超时时间,单位为秒
down:表示当前的server不参与负载
backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

5、遇到的问题总结

5.1、Nginx

刚开始配置这个动态负载均衡的时候,我是先安装了Nginx,然后再安装Consul,最后才安装master
那个那个时候我重新对Nginx的文件进行了编译,然后每次启动都报错,提示我没有找不到第三方插件upsync
原来我是忘记了 make && make install,所以每次重新编译后的的文件,都需要进行 make && make install
后来反复的重装,弄了一天才搞明白

5.2、Nginx安装过程的错误

错误一:
./configure: error: SSL modules require the OpenSSL library.
You can either do not enable the modules, or install the OpenSSL library
into the system, or build the OpenSSL library statically from the source
with nginx by using --with-openssl= option.
如果发现这个错误,别急,去网上翻译以下,你会发现它的意思是
/configure:error:ssl模块需要openssl库。
您可以不启用模块,也可以安装OpenSSL库。
或者从源代码静态构建OpenSSL库
与nginx一起使用–with openssl= 选项。

因为安装Nginx之前我安装了老版的ssl所以报错了

------解决办法

yum -y install openssl openssl-devel
错误二:
./configure: error: the HTTP rewrite module requires the PCRE library.
/configure:error:HTTP重写模块需要PCRE库。

-----解决办法

yum -y install pcre-devel

5.3、consul遇到的问题

consul-1.6.0不支持调用API接口去删除服务,不是说不支持,因为我完全查找不到服务的ID,网上还说右键对应的词条-检查,然后就能看到ID,我还以为是我的服务问题,我卸了重装还是没有用,我弄了将近3个小时没删除成功,最后找到了通过linux命令删除的方式文章中有连接,也有具体的实现方式,本文说明处---- 2.14

5.4、master的解压

master的解压目录一定要与nginx的解压目录同级,不然重新编译Nginx的时候会找不到第三方模块的

纯手打这么长,每一个环节都解释的非常清楚,都是我自己测试过的,按步骤来就不会报错了。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值