Consul Nginx upsync实现动态负载均衡

Nginx下实现静态的负载均衡(反向代理)不难,但动态的需要额外花点功夫。

这里要用到Consul和nginx的upsync模块,所以nginx需要编译安装。

依赖安装

yum install -y unzip lsof
yum install -y pcre-devel openssl-devel

Consul环境搭建

wget https://releases.hashicorp.com/consul/1.9.4/consul_1.9.4_linux_amd64.zip
unzip consul_1.9.4_linux_amd64.zip

# 启动,0.0.0.0表示监听所有IP请求,也可设置为127.0.0.1只允许本地
./consul agent -dev -ui -node=consul-dev -client=0.0.0.0

# 后台运行
./consul agent -dev -ui -node=consul-dev -client=0.0.0.0 > /dev/null 2>&1 &

consul的默认监听端口为8500

nginx编译安装

首先下载nginx-upsync-module

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

下载nginx源码

wget http://nginx.org/download/nginx-1.18.0.tar.gz
tar -zxvf nginx-1.18.0.tar.gz

编译安装nginx

cd nginx-1.18.0
groupadd nginx
useradd -g nginx -s /sbin/nologin nginx
mkdir -p /var/tmp/nginx/client/
mkdir -p /usr/local/nginx

./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

安装后的nginx位于 /usr/local/nginx/sbin/nginx,可创建软链接

ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx

nginx启动停止脚本

编辑/etc/init.d/nginx

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  NGINX is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /usr/local/nginx/conf/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /usr/local/nginx/logs/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/local/nginx/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -z "`grep $user /etc/passwd`" ]; then
       useradd -M -s /bin/nologin $user
   fi
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}
start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
restart() {
    configtest || return $?
    stop
    sleep 1
    start
}
reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}
force_reload() {
    restart
}
configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
    status $prog
}
rh_status_q() {
    rh_status >/dev/null 2>&1
}
case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

加权限

chmod +x /etc/init.d/nginx

nginx服务

将nginx服务加入chkconfig管理列表

# centos下
chkconfig --add /etc/init.d/nginx
chkconfig nginx on
# 启动
systemctl start nginx

nginx配置

创建upsync的dump目录, /usr/local/nginx/conf/servers/

mkdir /usr/local/nginx/conf/servers/

并在其下创建空白文件servers.conf,没有这个文件的话nginx启动会报错。

upsync_dump_path指定从consul拉取的上游服务器后持久化到的位置,这样即使consul服务器出问题了,本地还有一个备份。

编辑nginx.conf,添加nginx Upstream服务,格式如下:

upstream tmpup{
    server 127.0.0.1:11111;
    upsync 127.0.0.1:8500/v1/kv/upstreams/tmp upsync_timeout=6m upsync_interval=500ms upsync_type=consul strong_dependency=off;
    upsync_dump_path /usr/local/nginx/conf/servers/servers.conf;
}

server {
    listen       80;
    server_name  localhost;

    location / {
        proxy_pass http://tmpup;
        index  index.html index.htm;
    }
}

其中server 127.0.0.1:11111;是必需的,端口11111可随意设置,反正实际也用不到,注意不冲突即可。

启动nginx

# 服务形式
systemctl start nginx
systemctl stop nginx
systemctl restart nginx

# 直接使用nginx命令
nginx -t
nginx
nginx -s reload
killall -QUIT nginx

添加删除节点

使用CURL方式发送添加和删除节点请求

curl -X PUT http://127.0.0.1:8500/v1/kv/upstreams/tmp/127.0.0.1:8080
curl -X DELETE http://127.0.0.1:8500/v1/kv/upstreams/tmp/127.0.0.1:8080

参数为{"weight":1, "max_fails":2, "fail_timeout":10, "down":0},其中weight即权重,值越高权重越高。

也可通过编程的方式来发送PUT/DELETE请求,这样就真正意义上实现了动态的负载均衡。

注意点

  1. 编译安装部分,在CentOS和Ubuntu下大致相同。只是nginx服务那部分经测试在CentOS可完美运行,在Ubuntu下有点问题,服务起不来,不过影响不大,可通过直接使用nginx命令来实现。
  2. 注意nginx编译时的用户组问题,牵涉到后面nginx运行时的权限,这里用的是nginx用户和nginx用户组。
  3. 由于节点列表是使用Consul的KV存储的,Consul重启后数据会丢失,所以需要自己去初始化节点列表。

Leave a Comment

豫ICP备19001387号-1