1.  安装ipvsadm管理工具

    LVS全称为Linux Virtual Server,工作在ISO模型中的第四层,由于其工作在第四层,因此与iptables类似,必须工作在内核空间上。因此lvs与iptables一样,是直接工作在内核中的,叫ipvs,主流linux发行版默认都已经集成了ipvs,因此用户只需安装一个管理工具ipvsadm即可, ipvsadm是LVS在应用层的管理命令,可以通过这个命令去管理LVS的配置。

    1.  安装依赖

        yum install -y libnl* popt*        

    2.  加载lvs模块

        modprobe ip_vs       

        [root@redis_server_194 ~]# cat /proc/net/ip_vs
        IP Virtual Server version 1.2.1 (size=4096)
        Prot LocalAddress:Port Scheduler Flags
        -> RemoteAddress:Port Forward Weight ActiveConn InActConn

    3.  下载并安装ipvsadm

        yum install ipvsadm        

    4.  查看LVS集群

        ipvsadm -L -n       

        IP Virtual Server version 1.2.1 (size=4096)
        Prot LocalAddress:Port Scheduler Flags
        -> RemoteAddress:Port Forward Weight ActiveConn InActConn        

2.  ipvsadm命令说明

1) ipvsadm的基本用法:
# ipvsadm COMMAND [protocol] service address
               [scheduling-method] [persistence options]
 
# ipvsadm command [protocol] service address
               server-address [packet-forwarding-method] [weight options]
 
第一条命令用于向LVS系统中添加一个用于负载均衡的virtual server(VS);
第二条命令用来修改已经存在的VS的配置,service address用来指定涉及的虚拟服务即虚拟地址,server-address指定涉及的真实地址。
 
 
2) ipvsadm的帮助信息
[root@localhost ~]# ipvsadm --help
ipvsadm v1.26 2008/5/15 (compiled with popt and IPVS v1.2.1)
Usage:
  ipvsadm -A|E -t|u|f service-address [-s scheduler] [-p [timeout]] [-M netmask] [--pe persistence_engine]
  ipvsadm -D -t|u|f service-address
  ipvsadm -C
  ipvsadm -R
  ipvsadm -S [-n]
  ipvsadm -a|e -t|u|f service-address -r server-address [options]
  ipvsadm -d -t|u|f service-address -r server-address
  ipvsadm -L|l [options]
  ipvsadm -Z [-t|u|f service-address]
  ipvsadm --set tcp tcpfin udp
  ipvsadm --start-daemon state [--mcast-interface interface] [--syncid sid]
  ipvsadm --stop-daemon state
  ipvsadm -h
 
Commands:
Either long or short options are allowed.
  --add-service     -A        add virtual service with options
  --edit-service    -E        edit virtual service with options
  --delete-service  -D        delete virtual service
  --clear           -C        clear the whole table
  --restore         -R        restore rules from stdin
  --save            -S        save rules to stdout
  --add-server      -a        add real server with options
  --edit-server     -e        edit real server with options
  --delete-server   -d        delete real server
  --list            -L|-l     list the table
  --zero            -Z        zero counters in a service or all services
  --set tcp tcpfin udp        set connection timeout values
  --start-daemon              start connection sync daemon
  --stop-daemon               stop connection sync daemon
  --help            -h        display this help message
 
Options:
  --tcp-service  -t service-address   service-address is host[:port]
  --udp-service  -u service-address   service-address is host[:port]
  --fwmark-service  -f fwmark         fwmark is an integer greater than zero
  --ipv6         -6                   fwmark entry uses IPv6
  --scheduler    -s scheduler         one of rr|wrr|lc|wlc|lblc|lblcr|dh|sh|sed|nq,
                                      the default scheduler is wlc.
  --pe            engine              alternate persistence engine may be sip,
                                      not set by default.
  --persistent   -p [timeout]         persistent service
  --netmask      -M netmask           persistent granularity mask
  --real-server  -r server-address    server-address is host (and port)
  --gatewaying   -g                   gatewaying (direct routing) (default)
  --ipip         -i                   ipip encapsulation (tunneling)
  --masquerading -m                   masquerading (NAT)
  --weight       -w weight            capacity of real server
  --u-threshold  -x uthreshold        upper threshold of connections
  --l-threshold  -y lthreshold        lower threshold of connections
  --mcast-interface interface         multicast interface for connection sync
  --syncid sid                        syncid for connection sync (default=255)
  --connection   -c                   output of current IPVS connections
  --timeout                           output of timeout (tcp tcpfin udp)
  --daemon                            output of daemon information
  --stats                             output of statistics information
  --rate                              output of rate information
  --exact                             expand numbers (display exact values)
  --thresholds                        output of thresholds information
  --persistent-conn                   output of persistent connection info
  --nosort                            disable sorting output of service/server entries
  --sort                              does nothing, for backwards compatibility
  --ops          -o                   one-packet scheduling
  --numeric      -n                   numeric output of addresses and ports
 
 
命令:
-A, --add-service: 添加一个集群服务. 即为ipvs虚拟服务器添加一个虚拟服务,也就是添加一个需要被负载均衡的虚拟地址。虚拟地址需要是ip地址,端口号,协议的形式。
-E, --edit-service: 修改一个虚拟服务。
-D, --delete-service: 删除一个虚拟服务。即删除指定的集群服务;
-C, --clear: 清除所有虚拟服务。
-R, --restore: 从标准输入获取ipvsadm命令。一般结合下边的-S使用。
-S, --save: 从标准输出输出虚拟服务器的规则。可以将虚拟服务器的规则保存,在以后通过-R直接读入,以实现自动化配置。
-a, --add-server: 为虚拟服务添加一个real server(RS)
-e, --edit-server: 修改RS
-d, --delete-server: 删除
-L, -l, --list: 列出虚拟服务表中的所有虚拟服务。可以指定地址。添加-c显示连接表。
-Z, --zero: 将所有数据相关的记录清零。这些记录一般用于调度策略。
--set tcp tcpfin udp: 修改协议的超时时间。
--start-daemon state: 设置虚拟服务器的备服务器,用来实现主备服务器冗余。(注:该功能只支持ipv4)
--stop-daemon: 停止备服务器。
-h, --help: 帮助。
 
参数:
以下参数可以接在上边的命令后边。
-t, --tcp-service service-address: 指定虚拟服务为tcp服务。service-address要是host[:port]的形式。端口是0表示任意端口。如果需要将端口设置为0,还需要加上-p选项(持久连接)。
-u, --udp-service service-address: 使用udp服务,其他同上。
-f, --fwmark-service integer: 用firewall mark取代虚拟地址来指定要被负载均衡的数据包,可以通过这个命令实现把不同地址、端口的虚拟地址整合成一个虚拟服务,可以让虚拟服务器同时截获处理去往多个不同地址的数据包。fwmark可以通过iptables命令指定。如果用在ipv6需要加上-6。
-s, --scheduler scheduling-method: 指定调度算法,默认是wlc。调度算法可以指定以下8种:rr(轮询),wrr(权重),lc(最后连接),wlc(权重),lblc(本地最后连接),lblcr(带复制的本地最后连接),dh(目的地址哈希),sh(源地址哈希),sed(最小期望延迟),nq(永不排队)
-p, --persistent [timeout]: 设置持久连接,这个模式可以使来自客户的多个请求被送到同一个真实服务器,通常用于ftp或者ssl中。
-M, --netmask netmask: 指定客户地址的子网掩码。用于将同属一个子网的客户的请求转发到相同服务器。
-r, --real-server server-address: 为虚拟服务指定数据可以转发到的真实服务器的地址。可以添加端口号。如果没有指定端口号,则等效于使用虚拟地址的端口号。
[packet-forwarding-method]: 此选项指定某个真实服务器所使用的数据转发模式。需要对每个真实服务器分别指定模式。
-g, --gatewaying: 使用网关(即直接路由),此模式是默认模式。
-i, --ipip: 使用ipip隧道模式。
-m, --masquerading: 使用NAT模式。
-w, --weight weight: 设置权重。权重是0~65535的整数。如果将某个真实服务器的权重设置为0,那么它不会收到新的连接,但是已有连接还会继续维持(这点和直接把某个真实服务器删除时不同的)。
-x, --u-threshold uthreshold: 设置一个服务器可以维持的连接上限。0~65535。设置为0表示没有上限。
-y, --l-threshold lthreshold: 设置一个服务器的连接下限。当服务器的连接数低于此值的时候服务器才可以重新接收连接。如果此值未设置,则当服务器的连接数连续三次低于uthreshold时服务器才可以接收到新的连接。(PS:笔者以为此设定可能是为了防止服务器在能否接收连接这两个状态上频繁变换)
--mcast-interface interface: 指定使用备服务器时候的广播接口。
--syncid syncid:指定syncid, 同样用于主备服务器的同步。
 
以下选项用于list命令:
-c, --connection: 列出当前的IPVS连接。
--timeout: 列出超时
--daemon:
--stats: 状态信息
--rate: 传输速率
--thresholds: 列出阈值
--persistent-conn: 坚持连接
--sor: 把列表排序。
--nosort: 不排序
-n, --numeric: 不对ip地址进行dns查询
--exact: 单位
-6: 如果fwmark用的是ipv6地址需要指定此选项。    
     
 
=========其他注意事项=========
如果使用IPv6地址,需要在地址两端加上"[]"。例如:ipvsadm -A -t [2001:db8::80]:80 -s rr
可以通过设置以下虚拟文件的值来防御DoS攻击:
/proc/sys/net/ipv4/vs/drop_entry
/proc/sys/net/ipv4/vs/drop_packet
/proc/sys/net/ipv4/vs/secure_tcp

3.  ipvsadm举例说明

    1.  LVS集群服务管理

        1.  添加集群

            ipvsadm -A -t|u|f service-address [-s scheduler]

            例子:

            ipvsadm -A -t 172.16.1.203:80 -s wlc            

        2.  修改集群

            ipvsadm -E -t|u|f service-address [-s scheduler]

            例子:

            ipvsadm -E -t 172.16.1.203:80 -s wrr

        3.  删除集群

            ipvsadm -D -t|u|f service-address

            例子:

            ipvsadm -D -t 172.16.1.203:80

    2.  管理集群中的RS

        1.  添加RS

            ipvsadm -a -t|u|f service-address -r server-address [-g|i|m] [-w weight]

            例子:

            ipvsadm -a -t 172.16.1.203:80 -r 172.16.1.239 -m -w 5

        2.  修改RS

            ipvsadm -e -t|u|f service-address -r server-address [-g|i|m] [-w weight]

            例子:

            ipvsadm -e -t 172.16.1.203:80 -r 172.16.1.239 -g -w 5

        3.  删除RS

            ipvsadm -d -t|u|f service-address -r server-address

            例子:

            ipvsadm -d -t 172.16.1.203:80 -r 172.16.1.239

    3.  管理LVS集群服务

        1.  查看lvs集群转发情况

            ipvsadm -ln

            说明:          

            Prot LocalAddress:Port Scheduler Flags
            -> RemoteAddress:Port Forward Weight ActiveConn InActConn
            TCP 119.254.149.165:3306 lc
            -> 192.168.2.191:3306 Masq 1 0 0
            -> 192.168.2.193:3306 Masq 1 0 1

            ActiveConn  tcp连接状态的ESTABLISHED  

            InActConn  除了ESTABLISHED以外的,所有的其它状态的tcp连接  

        2.  查看lvs集群连接状态

            ipvsadm -l --stats

            说明:

            Conns    (connections scheduled)  已经转发过的连接数

            InPkts   (incoming packets)       入包个数

            OutPkts  (outgoing packets)       出包个数

            InBytes  (incoming bytes)         入流量(字节)

            OutBytes (outgoing bytes)         出流量(字节)

        3.  查看lvs集群速率

            ipvsadm -l --rate           

            说明:

            CPS      (current connection rate)   每秒连接数

            InPPS    (current in packet rate)    每秒的入包个数

            OutPPS   (current out packet rate)   每秒的出包个数

            InBPS    (current in byte rate)      每秒入流量(字节)

            OutBPS   (current out byte rate)      每秒入流量(字节)

        4.  清除计数器

            ipvsadm -Z

        5.  清除规则

            ipvsadm -C  删除所有集群服务

        6.  保存规则                  

            ipvsadm -S > /path/to/somefile

ipvsadm-save > /path/to/somefile

            ipvsadm-restore < /path/to/somefile

4.  配置NAT模式

    1.  环境

        三台主机:CentOS7.4

        调度器:119.254.149.165(公网IP)  192.168.2.55(内网IP)

        RS1:  192.168.2.191  192.168.2.55(网关)

        RS2:  192.168.2.193  192.168.2.55(网关)

        关键点:RS网关必须与Director内网IP一致

    2.  拓扑图

        

lvs 使用docker部署 lvs部署安装_服务器

    3.  操作步骤

        1.  Director端:  安装ipvsadm

            yum install ipvsadm -y

        2.  Director端:  写入脚本

#! /bin/bash
# director 服务器上开启路由转发功能
echo 1 > /proc/sys/net/ipv4/ip_forward
# 关闭icmp的重定向
echo 0 >/proc/sys/net/ipv4/conf/all/send_redirects
echo 0 >/proc/sys/net/ipv4/conf/default/send_redirects
# 注意区分网卡名字
echo 0 >/proc/sys/net/ipv4/conf/eth0/send_redirects
echo 0 >/proc/sys/net/ipv4/conf/eth2/send_redirects
# director 设置nat防火墙
iptables -t nat -F
iptables -t nat -X
iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -j MASQUERADE
# director设置ipvsadm
IPVSADM='/sbin/ipvsadm'
$IPVSADM -C
# 前面是公网IP、后面是私网IP -w是权重 使用lc算法(最少链接)
$IPVSADM -A -t 119.254.149.165:80 -s lc
$IPVSADM -a -t 119.254.149.165:80 -r 192.168.2.191:80 -m -w 1
$IPVSADM -a -t 119.254.149.165:80 -r 192.168.2.193:80 -m -w 1

        3.  Director端:  执行脚本

            sh /usr/local/sbin/lvs_nat.sh

        4.  测试  

5.  配置DR模式

    1.  环境

        三台主机:CentOS 7.4

        调度器:192.168.2.191(DIP)  192.168.2.195(VIP)  192.168.2.55(网关)

        RS1:192.168.2.192(RIP)  192.168.2.195(VIP)  192.168.2.55(网关)

        RS2:192.168.2.193(RIP)  192.168.2.195(VIP)  192.168.2.55(网关)

    2.  环境

        

lvs 使用docker部署 lvs部署安装_lvs 使用docker部署_02

    3.  操作步骤

        1.  Director端:  安装ipvsadm

            yum install ipvsadm -y

        2.  Director端:  写入脚本

#! /bin/bash
# 打开转发功能
echo 1 > /proc/sys/net/ipv4/ip_forward
ipv=/usr/sbin/ipvsadm
vip=192.168.2.195
rs1=192.168.2.192
rs2=192.168.2.193
# 给网卡配置一个IP地址
ifconfig eth0:0 $vip broadcast $vip netmask 255.255.255.255 up
# 增加路由
route add -host $vip dev eth0:0
# 设置防火墙规则
$ipv -C
# wrr算法 -g(DR) -w(加权轮询)
$ipv -A -t $vip:80 -s wrr
$ipv -a -t $vip:80 -r $rs1:80 -g -w 1
$ipv -a -t $vip:80 -r $rs2:80 -g -w 1

        3.  Real Server端:  写入脚本  

#! /bin/bash
# 设置虚拟IP
vip=192.168.2.192
# 添加虚拟IP
ifconfig lo:0 $vip broadcast $vip netmask 255.255.255.255 up
route add -host $vip lo:0
echo "1" >/proc/sys/net/ipv4/conf/lo/arp_ignore
echo "2" >/proc/sys/net/ipv4/conf/lo/arp_announce
echo "1" >/proc/sys/net/ipv4/conf/all/arp_ignore
echo "2" >/proc/sys/net/ipv4/conf/all/arp_announce

    4.  DR模式配置要点

        1)LVS服务器单网卡即可配置负载均衡;
        2)要求LVS必须和后端Realserver服务器在一个局域网;
        3)LVS和Realserver要么统一配置公网IP,要么统一配置内网IP,比较浪费公网IP地址,所以一般在局域网中使用。
        4)LVS和后端Realserver服务器上均配置VIP地址,故上述流程详述中识别后端服务器是靠MAC地址;LVS的VIP直接配置在真实物理网卡上,后端Realver机器的VIP配置在lo网卡上,避免冲突。
        5)LVS服务器不需要开启路由转发功能;
        6)Realserver上的VIP地址必须要抑制VIP的ARP响应

一往无前虎山行,拨开云雾见光明