一、Consul环境搭建html
下载consul_0.7.5_linux_amd64.zip到/usr/local/src目录node
cd /usr/local/src wget https://releases.hashicorp.com/consul/0.7.5/consul_0.7.5_linux_amd64.zip
解压consul_0.7.5_linux_amd64.ziplinux
须要先确认是否安装了unzip,若是没有安装先安装zip unzipnginx
yum install -y zip unzip mkdir /usr/local/consul unzip consul_0.7.5_linux_amd64.zip -d /usr/local/consul
启动consulgit
/usr/local/consul/consul agent -dev -ui -node=consul-dev -client=192.168.100.121
(此ip为当前服务器的局域网ip,请勿配置公网ip)github
临时关闭防火墙 后端
systemctl stop firewalld
测试:浏览器访问192.168.100.121:8500浏览器
二、安装nginx1.9.10以上版本,而且安装nginx-upsync-module模块bash
nginx-upsync-module是新浪微博开源插件,在此做用为:服务器
拉取 consul 的后端 KV的列表,并更新 Nginx 的路由信息。此模块不依赖于任何第三方模块。 consul 做为 Nginx 的 db,利用 consul 的 KV 服务,每一个 Nginx work 进程独立的去拉取各个 upstream 的配置,并更新各自的路由信息从而达到动态负载均衡,不去重启nginx。
下载nginx:
wget http://nginx.org/download/nginx-1.9.10.tar.gz
下载nginx-upsync-module:
wget https://github.com/weibocom/nginx-upsync-module/archive/master.zip
解压nginx-upsync-module
unzip master.zip
解压nginx
tar -zxvf nginx-1.9.10.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 /usr/local/src/nginx-1.9.10 ./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=/usr/local/src/nginx-upsync-module-master make && make instal
配置nginx.conf文件:
http { include mime.types; default_type application/octet-stream; sendfile on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; upstream product{ #用于心跳检测 server 127.0.0.1:11111; #去consul的KV拉取上游服务器信息 upsync 192.168.100.121:8500/v1/kv/upstreams/itchao upsync_timeout=6m upsync_interval=500ms upsync_type=consul strong_dependency=off; #存放拉取到的上游服务器信息,/usr/local/nginx/conf/servers 这个目录须要建立 upsync_dump_path /usr/local/nginx/conf/servers/servers_test.conf; } server { listen 80; server_name localhost; location / { # root html; #反向代理配置 proxy_pass http://product; index index.html index.htm; } } }
进入consul管理端建立KV服务信息
也能够经过postman添加集群服务器信息:
PUT 请求 http://192.168.100.121:8500/v1/kv/upstreams/itchao/192.168.1.115:8080
192.168.1.115:8080 表明须要负载的上游服务器地址以及端
查看从consul拉取的上游服务器信息:
cat /usr/local/nginx/conf/servers/servers_test.conf