linux系统搭建nginx动态负载均衡
一、安装nginx环境依赖 gcc gcc-c++等(如新环境,未安装请先安装)
yum -y install gcc gcc-c++ kernel-devel pcre pcre-devel zlib zlib-devel openssl openssl-devel
二、解压nginx安装包
tar -zxvf nginx-1.8.0.tar.gz -C /usr/local
三、安装consul
1.下载consul
wget https://releases.hashicorp.com/consul/0.7.5/consul_0.7.5_linux_amd64.zip
2.解压:
unzip consul_0.7.5_linux_amd64.zip
如果解压出现该错误:-bash: unzip: 未找到命令
解决办法:yum -y install unzip
3.执行以下 ./consul 出现以下信息就说明安装成功
usage: consul [--version] [--help] <command> [<args>]
Available commands are:
agent Runs a Consul agent
configtest Validate config file
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
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
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
snapshot Saves, restores and inspects snapshots of Consul server state
version Prints the Consul version
watch Watch for changes in Consul
4.启动consul
./consul agent -dev -ui -node=consul-dev -client=192.168.212.131
agent应用 参数…… node节点 指定consul运行的客户机ip
5.浏览器访问192.168.212.131:8500
注意需要关闭防火墙:systemctl stop firewalld
四、编译nginx配置插件nginx-upsync-module
./configure --prefix=/usr/local/nginx --add-module=/opt/nginx-upsync-module-master
prefix nginx路径 add +插件路径
五、Upstream 动态配置
##动态去consul 获取注册的真实反向代理地址
upstream itmayiedu{
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;
upsync_dump_path /usr/local/nginx/conf/servers/servers_test.conf;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://itmayiedu;
index index.html index.htm;
}
}
upsync指令指定从consul哪个路径拉取上游服务器配置;upsync_timeout配置从consul拉取上游服务器配置的超时时间;upsync_interval配置从consul拉取上游服务器配置的间隔时间;upsync_type指定使用consul配置服务器;strong_dependency配置nginx在启动时是否强制依赖配置服务器,如果配置为on,则拉取配置失败时nginx启动同样失败。upsync_dump_path指定从consul拉取的上游服务器后持久化到的位置,这样即使consul服务器出问题了,本地还有一个备份。
六、创建upsync_dump_path
mkdir /usr/local/nginx/conf/servers/
七、启动consul
关闭防火墙systemctl stop firewalld
./consul agent -dev -ui -node=consul-dev -client=192.168.212.131
client 中指定consul服务在哪台机子上起作用
八、添加nginx Upstream服务
发送put请求
curl -X PUT http://192.168.212.134:8500/v1/kv/upstreams/itmayiedu/192.168.212.1:8081
curl -X PUT http://192.168.212.134:8500/v1/kv/upstreams/itmayiedu/192.168.212.1:8081
给212.134添加上游服务器212.1,因为啊hi全限定指定,因此不限定在哪台机器上发请求。
九、启动Nginx
./nginx -s -t reload
# 检查端口是否运行
lsof -i :80