(文章目录)

consul 安装

1.下载 consul下载地址 2.解压

unzip consul_1.9.4_linux_amd64.zip

3.将这个文件移动到全局变量环境中

mv consul /usr/local/bin/

验证安装

consul version

在这里插入图片描述

consul 常用命令

consul命令 描述
agent 运行一个consul agent
members 列出consul cluster集群中的members
join 将agent加入到consul集群
leave 将节点移除所在的集群

启动consul服务

consul agent -server -bootstrap-expect 1 -data-dir /tmp/consul -node=ali -bind=192.168.34.170 -ui -client=0.0.0.0

参数介绍:

-server 表示启动的是一个服务 -bootstrap-expect 1 表示等待多少个节点再启动,这里1个,就是自己一个就启动了 -node=ali 就是给consul服务起个别名为 ali -bind=192.168.34.170 绑定内网ip -data-dir /opt/data1 数据存储目录为/opt/data1 -ui 启动默认ui界面 -client consul绑定在哪个client地址上,这个地址提供HTTP、DNS、RPC等服务,默认是127.0.0.1,可指定允许客户端使用什么ip去访问

访问: http://192.168.34.170:8500/ui/dc1/services

image.png 开启成功。

nginx 负载均衡配置【192.168.34.170】

upstream blogs{
   server www.study_nginx.com:8080 weight=1;
   upsync 192.168.34.170:8500/v1/kv/upstreams/nginx_test upsync_timeout=6m 		   upsync_interval=500ms upsync_type=consul strong_dependency=off;
   upsync_dump_path /vhost/server_test.conf;
   include /vhost/server_test.conf;
}
server{
     listen 80;
     server_name www.load_balancing.com;
     index index.html index.php;
     
     location ~ \.php$ {
        proxy_pass http://blogs;
     }  
}

重启nginx

如果重启nginx出现下面这种情况: 在这里插入图片描述 可能是没有安装 upsync 模快。

运行 /usr/local/nginx/nginx -V 检查nginx是否安装了upsync模块没有得话进行安装。

upsync 模块安装

cd /home
wget https://github.com/weibocom/nginx-upsync-module/archive/master.zip
unzip master.zip

重新编译nginx :

cd /home/nginx-1.18.0

<font color="red">注意:</font>在重新编译前要运行/usr/local/nginx/nginx -V。 在这里插入图片描述 将上图参数后面的复制下来,在后面加上我们这次安装的upsync模块

./configure --sbin-path=/usr/local/nginx/nginx --conf-path=/usr/local/nginx/nginx.conf --pid-path=/usr/local/nginx/nginx.pid --with-http_gzip_static_module --with-http_stub_status_module --with-file-aio --with-http_realip_module --with-http_ssl_module --with-pcre=/home/pcre-8.44 --with-zlib=/home/zlib-1.2.11 --with-openssl=/home/openssl-1.1.1g --with-pcre      --add-module=/home/nginx-upsync-module-master

make -j2
make install

upsync作用:<font color="red">nginx动态获取最新upstream信息</font>

然后重启nginx即可。

consul + nginx 动态负载均衡

添加upstream 发送PUT请求

curl -X PUT  -d '{"weight":1,"max_fails":2,"fail_timeout":10}' http://192.168.34.170:8500/v1/kv/upstreams/nginx_test/192.168.34.165:80

在这里插入图片描述 返回true。添加成功。也可以输入下面的指令查看

curl http://127.0.0.1:8500/v1/kv/?recurse

在这里插入图片描述 继续再添加 upstream。 在这里插入图片描述 开始访问,验证动态负载是否成功。

验证是否成功

curl www.load_balancing.com/api/admin.php

image.png ==【192.168.34.170】 /vhost/server.conf==

这是我们操作upstream时,consul自动更新的。 在这里插入图片描述 删除其中的一个

curl -X DELETE  -d '{"weight":1,"max_fails":2,"fail_timeout":10}' http://192.168.34.170:8500/v1/kv/upstreams/nginx_test/192.168.34.170:80

在这里插入图片描述

再继续访问: image.png 由此可以看出,动态负载均衡搭配成功。