Nginx+Keepalive负载均衡
目录
0.0.1 环境
主机 | IP |
---|---|
MASTER | 192.168.1.90 |
BACKUP | 192.168.1.91 |
0.0.2 Nginx安装
0.0.2.1 下载
wget http://nginx.org/download/nginx-1.16.0.tar.gz
也可以使用Tengine
wget http://tengine.taobao.org/download/tengine-2.3.0.tar.gz
0.0.2.2 安装依赖
yum -y install pcre-devel openssl-devel gcc
0.0.2.3 安装
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用户
useradd -s /sbin/nologin www
修改Nginx目录权限
chown -R www:www /usr/local/nginx
0.0.3 安装Keepalive
0.0.3.1 下载
wget https://www.keepalived.org/software/keepalived-2.0.16.tar.gz
tar zxf keepalived-2.0.16.tar.gz
cd keepalived-2.0.16
./configure \
--prefix=/usr/local/keepalived
make
make install
0.0.3.2 添加到systemctl和chkconfig进行管理
vi /lib/systemd/system/keepalived.service
[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的位置
0.0.3.3 配置Keepalive
两个节点配置文件不一样的地方只有state、priority和router_id,其他完全保持一致。
节点1配置
! 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配置
! 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
systemctl start keepalived.service #启动
systemctl stop keepalived.service #停止