Nginx+Keepalive负载均衡

主机IP
MASTER192.168.1.90
BACKUP192.168.1.91

text

wget http://nginx.org/download/nginx-1.16.0.tar.gz
也可以使用Tengine
wget http://tengine.taobao.org/download/tengine-2.3.0.tar.gz

shell

yum -y install pcre-devel openssl-devel gcc

shell

tar zxf nginx-1.16.0.tar.gz

cd nginx-1.16.0
./configure \
--prefix=/usr/local/nginx \
--with-http_gzip_static_module \
--with-http_flv_module \
--with-http_stub_status_module \
--with-http_v2_module \
--with-http_ssl_module \
--with-file-aio \
--with-http_realip_module

make && make install

创建Nginx用户

shell

useradd -s /sbin/nologin www

修改Nginx目录权限

shell

chown -R www:www /usr/local/nginx

shell

wget https://www.keepalived.org/software/keepalived-2.0.16.tar.gz

shell

tar zxf keepalived-2.0.16.tar.gz

cd keepalived-2.0.16
./configure \
--prefix=/usr/local/keepalived

make 
make install

shell

vi /lib/systemd/system/keepalived.service

shell

[Unit]
Description=Keepalived
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/var/run/keepalived.pid
ExecStart=/usr/local/keepalived/sbin/keepalived -D
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

ExecStart=/usr/local/keepalived/sbin/keepalived -D	#keepalived的启动文件  -D是输出详细日志
PIDFile=/var/run/keepalived.pid	#keepalived默认存放pid的位置

两个节点配置文件不一样的地方只有state、priority和router_id,其他完全保持一致。

节点1配置

text

! Configuration File for keepalived

global_defs {
   router_id NGINX_DEVEL
}

vrrp_script chk_nginx {
    script "/usr/local/keepalived/check_nginx.sh"
    interval 1
    weight -20
}

vrrp_instance VI_1 {
    state MASTER			#这里只能接受MASTER和BACKUP,而且必须为大写
    interface eth0			#绑定虚拟IP的网卡接口
    virtual_router_id 51	#虚拟ID,同一个ID之间互相通讯,两个节点之间必须保持一致
    priority 100			#优先级(0-254),一般设置100左右,主节点要比从节点高
    advert_int 1			#发VRRP包的时间间隔,即多久进行一次master选举(可以认为是健康查检时间间隔)
    authentication {
        auth_type PASS		#设置验证方式,这里采用的是明文密码认证,两个节点必须保持一致
        auth_pass 1234
    }
    virtual_ipaddress {
        192.168.1.100		#虚拟IP,可以设置多个
    }

    track_script {
       chk_nginx			#nginx存活状态检测脚本
    }
}

节点2配置

text

! Configuration File for keepalived

global_defs {
   router_id NGINX_DEVEL
}

vrrp_script chk_nginx {
    script "/usr/local/keepalived/check_nginx.sh"
    interval 1
    weight -20
}

vrrp_instance VI_1 {
    state BACKUP			#这里只能接受MASTER和BACKUP,而且必须为大写
    interface eth0			#绑定虚拟IP的网卡接口
    virtual_router_id 51	#虚拟ID,同一个ID之间互相通讯,两个节点之间必须保持一致
    priority 90				#优先级(0-254),一般设置100左右,主节点要比从节点高
    advert_int 1			#发VRRP包的时间间隔,即多久进行一次master选举(可以认为是健康查检时间间隔)。
    authentication {
        auth_type PASS		#设置验证方式,这里采用的是明文密码认证,两个节点必须保持一致
        auth_pass 1234
    }
    virtual_ipaddress {
        192.168.1.100		#虚拟IP,可以设置多个
    }
    track_script {
       chk_nginx			#nginx存活状态检测脚本
    }
}

分别启动Keepalived

shell

systemctl start keepalived.service	#启动
systemctl stop keepalived.service	#停止

相关内容