linux运维

nginx与lvs详解

2018-05-20  本文已影响129人  dabule

详细描述常见nginx常用模块和模块的使用示例

nginx常见的模块分类:

核心模块:core module
Nginx 核心功能模块负责 Nginx 的全局应用,主要对应主配置文件的 Main 区块和 Events 区块

标准模块:HTTP modules,Standard HTTP modules,Optional HTTP modules,Mail modules
等等.这些模块非常丰富,列举常见的模块

ngx_http_auth_basic_module模块: 实现基于用户的访问控制,使用basic机制进行用户认证

auth_basic string | off;  认证的用户字符
auth_basic_user_file file;   认证的文件路径
location /admin/ {
    alias /webapps/app1/data/;
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.ngxpasswd;
                        }

ngx_http_stub_status_module模块: 用于输出nginx的基本状态信息

    Active connections: 251 
    server accepts handled requests
            16630948 16630948 31070465 
    Reading: 5 Writing: 103 Waiting: 60 
                
        Active connections: 活动状态的连接数
        accepts:已经接受的客户端请求的总数
        handled:已经处理完成的客户端请求的总数
        requests:客户端发来的总的请求数
        Reading:处于读取客户端请求报文首部的连接的连接数
        Writing:处于向客户端发送响应报文过程中的连接数
        Waiting:处于等待客户端发出请求的空闲连接数
location  /basic_status {
        stub_status;
                        }
                        

ngx_http_ssl_module模块:ssl安全模块功能

    ssl on | off;  是否开启ssl安全功能
                    
    ssl_certificate file;  当前虚拟主机使用PEM格式的证书文件;
                    
    ssl_certificate_key file; 当前虚拟主机上与其证书匹配的私钥文件
                    
    ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];支持ssl协议版本,默认为后三个
                    
    ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
        builtin[:size]:使用OpenSSL内建的缓存,此缓存为每worker进程私有
        [shared:name:size]:在各worker之间使用一个共享的缓存
                    
    ssl_session_timeout time;
        客户端的连接可以复用ssl session cache中缓存 的ssl参数的有效时长
server {
    listen 443 ssl;  监听端口
    server_name www.magedu.com;  服务器名
    root /var/ssl/html;   根文件路径
    ssl on;   启用ssl
    ssl_certificate /etc/nginx/ssl/nginx.crt;  证书路径
    ssl_certificate_key /etc/nginx/ssl/nginx.key;  私钥路径
    ssl_session_cache shared:sslcache:20m;  20分钟
                        }                           

ngx_http_referer_module模块:反盗链功能

  valid_referers none | blocked | server_names | string ...;
    定义referer首部的合法可用值
            none:请求报文首部没有referer首部
            blocked:请求报文的referer首部没有值
            server_names:参数,其可以有值作为主机名或主机名模式
            arbitrary_string:直接字符串,但可使用*作通配符
            regular expression:被指定的正则表达式模式匹配到的字符串;要使用~打头,如:~.*\magedu\.com (要对.进行反义所以用'\'符号)
valid_referers none block server_names *.magedu.com *.mageedu.com magedu.* mageedu.* ~\.magedu\.;
                    
if($invalid_referer) {  #如果变量满足条件则一下结果
    return http://www.magedu.com/invalid.jpg;
                    }
                            

以上仅仅是nginx配置模块的冰山一角,详细的配置文档可以查看官方文档:http://nginx.org/en/docs/

简述Linux集群类型、系统扩展方式及调度方法

Linux集群类型分为:LB(负载均衡),HA(高可用),HP(高性能)几种类型.
系统的扩展方式一般有向上扩展和向外扩展两种,在linux服务中一般是向外扩展.
调度方法有静态方法与动态方法两大类型.

静态方法:是仅根据算法本身进行调度主要有以下几种方法:

  1. RR:轮询的方式
  2. WRR:加强轮询
  3. SH:实现session sticky,对源IP地址进行hash;将来自于同一个IP地址的请求始终发往第一次挑中的RS,实现会话绑定.
  4. DH:对目标IP地址hash,将发往同一个目标IP的请求始终转发至第一次挑中的RS,典型使用场景是正向代理缓存场景中的负载均衡

动态方法:主要根据每RS当前的负载状态及调度算法进行调度

  1. LC:least connections,最少连接数算法,计算方式如下:
    Overhead=activeconns(活动连接)*256+inactiveconns(非活动链接)
  2. WLC:Weighted LC,权重最少连接数算法,计算方式如下:
    Overhead=(activeconns*256+inactiveconns)/weight(权重)
  3. SED:Shortest Expection Delay,最短期望延迟,计算方式如下:
    Overhead=(activeconns+1)*256/weight
    除此之外还有NQ,LBLC,(动态的DH算法),LBLCR,(带复制功能的LBLC)等几个算法不进行一一列举了.

简述lvs四种集群有点及使用场景

四种集群方式分别为:lvs-nat,lvs-dr,lvs-tun,lvs-fullnat.在介绍这四种工作原理之前,了解一下lvs集群中的一些术语.

  vs:Virtual Server, Director, Dispatcher, Balancer
  rs:Real Server, upstream server, backend server
  CIP:Client IP,
  VIP: Virtual serve IP
  RIP: Real server IP
  DIP: Director IP

lvs-nat:

多目标IP的DNAT,通过将请求报文中的目标地址和目标端口修改为某挑出的RS的RIP地址和PORT端口来实现转发.网络拓扑图如下:

lvs-nat网络拓扑图.png

工作原理:当client向服务器(RS集群)发送请求时,源地址为CIP地址,目标地址为VIP,调度器Director收到报文后发现是发给后端RS服务器的数据,通过调度发给其中的一台RS(假设为RS1服务器),于是通过DIP向RS1的RIP1地址发送报文.
RS1服务器接收报文后,响应client的请求,于是RS1通过RIP1向Director的DIP地址发送响应报文,Director收到报文后将源地址IP从RIP改为VIP,目标IP不变发送给client.
这就完成了一次请求与响应的过程,期间client是与Director通信,并不知道RS服务器的存在,

该方式有以下几点特点:

  1. RIP和DIP必须在同一个IP网络,且应该使用私网地址;RS的网关要指向DIP
  2. 请求报文和响应报文都必须经由Director转发;所有的请求和发送都经过Director,Director易于造成系统拥塞
  3. 支持端口映射,可修改请求报文的目标PORT
  4. vs(Direcotr)必须是Linux系统,rs可以是任意系统

lvs-nat是典型的反代服务器的一种应用,Director可以做静态内容的缓存,减轻后端RS服务器的IO压力,并且能隐藏后端的RS服务器.

lvs-dr:

直接路由,通过为请求报文重新封装一个MAC首部进行转发,源MAC是DIP所在的接口的MAC,目标MAC是某挑选出的RS的RIP所在接口的MAC地址;源IP/PORT,以及目标IP/PORT均保持不变,由于lvs-dr是基于mac进行转发的,所以Director和各RS都得配置使用VIP,但是Director和各RS都有VIP要保证请求只发给Director而不是直接发给RS则需要确保前端路由器将目标IP为VIP的请求报文发往Director,实现方法有以下几种:

  1. 在前端网关做静态绑定,直接绑定mac,不进行ARP广播,但是如果Director出现故障则会出现找不到mac地址或重新绑定的情况.
  2. 在RS上使用arptables,
  3. 在RS上修改内核参数以限制arp通告及应答级别将arp_announce,和arp_ignore这两个参数修改一下就可以了,一般推荐第三种方式.
    其网络拓扑图如下:
lvs-dr网络拓扑图.png

工作原理:CIP向VIP请求报文,经过router时发现VIP在自己的网络中,于是就通过ARP方式将报文发给VIP主机,这里的Director和RS都有VIP地址所以要确保请求报文只能被Director接收,之后Director通过调度在报文上加上RS的MAC地址把报文扔给router,router通过新的MAC地址找的RS主机,并发送请求报告.
RS接收到请求报文之后发送用自己的VIP地址(一般不与RIP同网卡,而在lo网卡上)直接通过router响应报文,响应报文不经过Director.从而减轻Director的负载压力.

除了上面提到的mac问题以外该方式还有以下几点特点:

  1. RS的RIP可以使用私网地址,也可以是公网地址;RIP与DIP在同一IP网络;RIP的网关不能指向DIP,以确保响应报文不会经由Director
  2. RS跟Director要在同一个物理网络,(经过mac地址转发的)
  3. 请求报文要经由Director,但响应不能经由Director,而是由RS直接发往Client
  4. 不支持端口映射

lvs-dr是为减轻Director负载压力的一种实现方式.

lvs-tun:

转发方式,不修改请求报文的IP首部(源IP为CIP,目标IP为VIP),而是在原IP报文之外再封装一个IP首部(源IP是DIP,目标IP是RIP),将报文发往调度挑选出的目标RS;RS直接响应给客户端(源IP是VIP,目标IP是CIP)
其网络拓扑图如下:

lvs-tun网络拓扑图.png

工作原理:CIP向VIP发送请求报文,通过router到达Director,Director接受报文发现是集群服务后端报文直接在报文首部再添加RS服务的RIP地址首部(假设为RS1),并通过Internet发送到RS1服务器,RS接受报文后拆封报文时第一层的RIP是本机地址但是还有一层VIP地址首部,因此RS要支持隧道功能,能理解VIP地址并接受处理请求.
RS向CIP响应报文时,直接使用VIP做源地址,CIP做目标地址通过Internet向Client响应报文.

其特点如下:

  1. DIP, VIP, RIP都应该是公网地址
  2. RS的网关不能,也不可能指向DIP(响应不应该Director)
  3. 请求报文要经由Director,但响应不能经由Director
  4. 不支持端口映射
  5. RS的OS得支持隧道功能: 如果请求报文数据超过MTU(最大报文数)时,在添加首部会超过MTU而被拆分报文(要理解内层的CIP和VIP的首部)

lvs-tun一般应用在Director于RS不在同一网段,并且相隔甚远的情况下使用.

lvs-fullnat:

通过同时修改请求报文的源IP地址和目标IP地址进行转发.
CIP <--> DIP 请求报文时源IP从左往右,响应时目标IP从右往左
VIP <--> RIP 请求报文时目标IP从左往右,响应时源IP从右往左

lvs-fullnat网络拓扑图.png

工作原理:CIP向VIP发送请求,Director接收报文后知道是后端服务报文,于是修改源地址IP为DIP,目标地址IP为RIP,经过路由发送的RS服务器上.
RS服务器响应报文时,先通过RIP地址将报文发给Director的DIP,Director接收到报文后发现是Client的报文于是修改源IP为VIP,目标IP为CIP通过Internet发送给client.

lvs-fullnat的特点如下:

  1. VIP是公网地址,RIP和DIP是私网地址,且通常不在同一IP网络;因此,RIP的网关一般不会指向DIP
  2. RS收到的请求报文源地址是DIP,因此,只能响应给DIP;但Director还要将其发往Client
  3. 请求和响应报文都经由Director
  4. 支持端口映射,此类型默认不支持(需要修改编译内核)

lvs-fullnat框架一般用于Director与RS不在同一机房但可以通过内网连接的一种方式,内核默认是不支持的,需要重新编译内核才能实现.

描述LVS-NAT、LVS-DR的工作原理并实现配置

lvs-nat和lvs-dr的工作原理上述已经说明了,这个主要将如何实现配置.在讲配置之前先说明一下ipvsadm工具的一般用法,先yum安装ipvsadm之后执行一下ipvsadm -h命令查看帮助信息.具体如下:

[root@localhost ~]# ipvsadm -h
ipvsadm v1.27 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] [-b sched-flags]
  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
  --sched-flags  -b flags             scheduler flags (comma-separated)

ipvsadm常用的命令如下:

    ipvsadm -A|E -t|u|f service-address [-s scheduler] [-p [timeout]] [-M netmask] [--pe persistence_engine] [-b sched-flags]
    VS服务相关的命令
      -A:新增VS
      -E:修改VS
      -D:删除VS
      -R:重载规则
      -S:保存规则(相当于ipvsadm-save)
      -C:清空所有
      -L:查看
      -t:tcp协议
      -u:udp协议
      -f:防火墙相关协议的
      -s:调度方法,默认是wlc
      -p:会话保持连接的
    ipvsadm -a|e -t|u|f service-address -r server-address [options]  
      RS相关的命令
      -a,-e,-d,-l,-t|u|f这些命令与VS服务命令一致,只是大小写转换而已
      -r:指明服务器的IP
      -w:权重

lvs-nat配置:

前期准备:
各节点时间必须同步

Director:

VIP: 192.168.1.106(公网地址)
DIP: 192.168.12.128(私网地址)
开启核心转发功能

[root@director ~]# ifconfig 
ens32: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.106  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::2a81:1ac7:a4c8:2c80  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:41:95:b4  txqueuelen 1000  (Ethernet)
        RX packets 448825  bytes 659683112 (629.1 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 96801  bytes 5977464 (5.7 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

ens34: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.12.128  netmask 255.255.255.0  broadcast 192.168.12.255
        inet6 fe80::f5a6:4990:753d:53b6  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:41:95:be  txqueuelen 1000  (Ethernet)
        RX packets 229  bytes 38198 (37.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 75  bytes 9651 (9.4 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

-------------分割线-------------

#开启转发功能
[root@director ~]# sysctl -w net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1

RS1:

RIP: 192.168.12.129(私网地址并且和Director的私网地址在同一网段)
GW: 192.168.12.128(网关必须指向Director的私网地址)
RS1可以ping通Director的私网地址,安装nginx或httpd服务,并配置主页内容,

[root@rs1 ~]# ping 192.168.12.128
PING 192.168.12.128 (192.168.12.128) 56(84) bytes of data.
64 bytes from 192.168.12.128: icmp_seq=1 ttl=64 time=0.290 ms
64 bytes from 192.168.12.128: icmp_seq=2 ttl=64 time=0.480 ms
64 bytes from 192.168.12.128: icmp_seq=3 ttl=64 time=0.481 ms
64 bytes from 192.168.12.128: icmp_seq=4 ttl=64 time=1.17 ms
^C
--- 192.168.12.128 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3000ms
rtt min/avg/max/mdev = 0.290/0.605/1.171/0.336 ms

RS2:

RIP:192.168.12.130(私网地址并且和Director的私网地址在同一网段)
GW: 192.168.12.128(网关必须指向Director的私网地址)
RS2可以ping通Director的私网地址,安装nginx或httpd服务,并配置主页内容,

[root@rs2 ~]# ping 192.168.12.128 -c 3
PING 192.168.12.128 (192.168.12.128) 56(84) bytes of data.
64 bytes from 192.168.12.128: icmp_seq=1 ttl=64 time=0.560 ms
64 bytes from 192.168.12.128: icmp_seq=2 ttl=64 time=0.336 ms
64 bytes from 192.168.12.128: icmp_seq=3 ttl=64 time=0.404 ms

--- 192.168.12.128 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 0.336/0.433/0.560/0.095 ms

验证服务是否配置成功

[root@director ~]# curl http://192.168.12.129/test1.html   #连接RS1的nginx服务
<h1> RS1: 192.168.12.129 </h1>
  
[root@director ~]# curl http://192.168.12.130/test1.html    #连接RS2的nginx服务
<h1> RS2: 192.168.12.130 </h1>

安装ipvsadm:

[root@director ~]# yum -y install ipvsadm.x86_64 
Loaded plugins: fastestmirror, langpacks
Repository epel is listed more than once in the configuration
Repository epel-debuginfo is listed more than once in the configuration
Repository epel-source is listed more than once in the configuration

...省略...

Transaction test succeeded
Running transaction
  Installing : ipvsadm-1.27-7.el7.x86_64                                                           1/1 
  Verifying  : ipvsadm-1.27-7.el7.x86_64                                                           1/1 

Installed:
  ipvsadm.x86_64 0:1.27-7.el7                                                                          

Complete!

配置lvs-nat:

配置Director

[root@director ~]# ipvsadm -A -t 192.168.1.106:80 -s rr

# -s 指明权重为rr, Director服务要ip:port

添加RS服务器

[root@director ~]# ipvsadm -a -t 192.168.1.106:80 -r 192.168.12.129 -m
[root@director ~]# ipvsadm -a -t 192.168.1.106:80 -r 192.168.12.130 -m

#-r: 添加RS服务器. -m: 指明是nat模式

检查配置结果:

[root@director ~]# ipvsadm -Ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  192.168.1.106:80 rr
  -> 192.168.12.129:80            Masq    1      0          0         
  -> 192.168.12.130:80            Masq    1      0          0 

验证结果:

客户端通过VIP请求test1.html主页,会发现响应报文分别来自RS1和RS2的nginx服务的内容,由于在虚拟机上实验发现连接不可达,未找到原因,此处未上传结果.

lvs-dr配置:

前期准备:
各节点时间必须同步

Director:

VIP: 192.168.12.128
DIP: 192.168.1.107

在eth0:0网卡上配置如下:

[root@localhost ~]# ifconfig eth0:0 192.168.12.128 netmask 255.255.255.255 broadcast 192.168.12.128 up

RS1:

VIP: 192.168.12.128
RIP1: 192.168.12.129

在lo:0上配置VIP

[root@rs1 ~]# ifconfig lo:0 192.168.12.128 netmask 255.255.255.0 broadcast 192.168.12.128 up

RS2:

VIP: 192.168.12.128
RIP2: 192.168.12.130

在lo:0上配置VIP

[root@rs2 ~]# ifconfig lo:0 192.168.12.128 netmask 255.255.255.0 broadcast 192.168.12.128 up

在两台RS服务器上配置如下:

#前四个命令设置了路由里面VIP只能被Director接收的命令
[root@rs2 ~]# echo 1 > /proc/sys/net/ipv4/conf/all/arp_ignore
[root@rs2 ~]# echo 1 > /proc/sys/net/ipv4/conf/lo/arp_ignore
[root@rs2 ~]# echo 2 > /proc/sys/net/ipv4/conf/all/arp_announce
[root@rs2 ~]# echo 2 > /proc/sys/net/ipv4/conf/lo/arp_announce
[root@rs2 ~]# route add -host 192.168.12.128 dev lo:0

#最后的命令指定192.168.12.128的ip只能经过lo:0这个网卡发送出去,确保是VIP响应而不是RIP响应.

在Director上安装并配置ipvsadm:

[root@localhost ~]# yum -y install ipvsadm
Loaded plugins: fastestmirror, refresh-packagekit, security
Loading mirror speeds from cached hostfile
 * base: mirrors.cn99.com
..省略...
Downloading Packages:
ipvsadm-1.26-4.el6.x86_64.rpm                                         |  42 kB     00:00     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : ipvsadm-1.26-4.el6.x86_64                                                 1/1 
  Verifying  : ipvsadm-1.26-4.el6.x86_64                                                 1/1 

Installed:
  ipvsadm.x86_64 0:1.26-4.el6                                                                

Complete!

[root@localhost ~]# ipvsadm -A -t 192.168.1.107:80 -s rr
[root@localhost ~]# ipvsadm -a -t 192.168.1.107:80 -r 192.168.12.129:80 -g
[root@localhost ~]# ipvsadm -a -t 192.168.1.107:80 -r 192.168.12.130:80 -g
[root@localhost ~]# ipvsadm -Ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  192.168.1.107:80 rr
  -> 192.168.12.129:80            Route   1      0          0         
  -> 192.168.12.130:80            Route   1      0          0  

#-g: 表示dr类型的,默认就是dr.

结果验证因客户机无法到达Director,暂时无法提供,待查明后补上.

上一篇下一篇

猜你喜欢

热点阅读