一:下载nginx和upsync,并编译nginx(添加upsync模块)
1.安装所需依赖:
//一键安装上面四个依赖
yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel
2. 切换到安装目录:
cd /usr/local
3.下载nginx安装包:
wget http://nginx.org/download/nginx-1.16.1.tar.gz
5.下载upsync并编写安装nginx:
tar zxvf nginx-1.16.1.tar.gz //解压
mv nginx-1.16.1 nginx //重命名
cd nginx
wget https://github.com/weibocom/nginx-upsync-module/archive/master.zip
yum -y install unzip 下载解压zip文件的依赖
//开始编译 /usr/local/nginx/nginx-upsync-module-master为upsync的路径
./configure --add-module=/usr/local/nginx/nginx-upsync-module-master
make
make install
6.修改nginx.conf文件的配置,具体配置如下:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
upstream test{
server 127.0.0.1:11111; #consul中固定的不用修改
#62.234.109.11 counsul所在服务器地址
#test 分组的名字
upsync 62.234.109.11:8500/v1/kv/upstreams/test upsync_timeout=6m upsync_interval=500ms upsync_type=consul strong_dependency=off;
upsync_dump_path /usr/local/nginx/servers/servers_test.conf;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://test;
proxy_connect_timeout 3s; #nginx连接超时时间
proxy_send_timeout 3s; #nginx发送给上游服务器(真实访问的服务器)超时时间
proxy_read_timeout 3s; #nginx接受上游服务器(真实访问的服务器)超时时间
index index.html index.htm;
}
}
}
7.新建放upsync_dump的文件目录:
mkdir /usr/local/nginx/servers (路径在nginx.conf中配置)
二:下载consul
1.下载解压consul
cd /usr/local
wget https://releases.hashicorp.com/consul/1.4.0/consul_1.4.0_linux_amd64.zip
unzip consul_1.4.0_linux_amd64.zip
2.运行consul
./consul
./consul agent -dev -ui -node=consul-dev -client=服务器内网ip
三:利用postman发送请求添加反向代理的ip地址:
http://62.234.109.11:8500/v1/kv/upstreams/test/39.108.107.163:8080 添加一个真实的服务器地址
192.168.212.134 :consul服务器地址 39.108.107.163 :真实服务器地址 test:分组名(在nginx.conf中配置过)
http://62.234.109.11:8500/v1/kv/upstreams/test/49.233.66.116:8080 再添加一个做负载均衡
在consul页面的 key/value里查看
负载均衡信息参数
{"weight":1, "max_fails":2, "fail_timeout":10, "down":0}
这是就可以直接访问部署nginx的ip地址查看反向代理,负载均衡的效果。