一、haproxynginx的区别

Haproxy的工作模式:代理模式为httptcp做代理,可以为多种服务做代理,它是一个专门的代理服务器,自己不能成为web服务。

nginx的工作模式:web模式和代理,Nginx只为WEB服务做代理。



二、安装配置

1、安装


# yum -y install haproxy


注意,如果在生产中安装,一定要注意安装软件的版本要落后最新版本一到两个,否则,新版本中出现了bug无法解决将是致命的。

2、配置详解

************************全局配置*****************************


Global
log     127.0.0.1 local2  # 定义全局日志服务器
chroot   /var/lib/haproxy  # 修改haproxy的工作目录到制定的目录,提高安全性
pidfile   /var/run/haproxy.pid # pid文件位置
maxconn   4000      # 最大连接数
user    haproxy     # 服务运行时的身份,也可以用uid来表示
group    haproxy     # 服务运行时的身份所属的组,可以用gid来表示
Daemon           # 服务以守护进程的身份运行
# turn on stats unix socket    # 默认打开UNIX socket
stats socket /var/lib/haproxy/stats # 指明unix socket 所在的位置
Node      www.a.com  # 定义当前节点的名称,用于HA场景中多haproxy进程共享同一个IP地址时
ulimit-n    100       # 设定每进程所能够打开的最大文件描述符数目,默认情况下其会自动进行计算,因此不推荐修改此选项

log127.0.0.1local2要想启用,可以看到默认配置文件中有这么一行注释

#local2.*/var/log/haproxy.log

做如下配置即可启用

# touch /var/log/haproxy.log
# vim /etc/rsyslog.conf
$ModLoad imudp
$UDPServerRun 514
# service rsyslog restart
# tail -f /var/log/haproxy.log
Oct  6 10:45:22 localhost haproxy[22208]: 172.16.5.200:50332 [06/Oct/2013:10:45:22.852] web static/www.web1.com 6/0/2/4/32 200 45383 - - ---- 3/3/0/1/0 0/0 "GET / HTTP/1.1"

显示了客户端ip和realserver主机名等信息

**********************默认配置*********************************

defaults
mode  http      # 为http服务代理,http为7层协议,tcp4层
log   global     # 全局日志
option httplog      # 日志类别为http日志格式
option dontlognull   # 不记录健康查询的日志
#########健康状况检测的意义在于,后端服务器若挂掉了,就不会再向它发送请求信息。
option http-server-close  # 每次请求完后主动关闭http通道,支持客户端长连接
option forwardfor  except 127.0.0.0/8 # 如果后端服务器需要获得客户端真实ip需要配置的参数,可以从http header中获得客户端ip
option  redispatch   #serverid对应的服务器挂掉后,强制定向到其他健康的服务器
retries  3       #3次连接失败就认为服务不可用,也可以通过后面设置
timeout http-request 10s # 请求超时间
timeout queue  1m   # 排队超时
timeout connect 10s   # 连接超时
timeout client  1m   # 客户端超时
timeout server  1m   # 服务器端超时
timeout http-keep-alive 10s # 保持连接超时
timeout check  10s    # 健康检测超时
maxconn    3000   # 每个进程最大连接数,可以在global中配置

************************前端代理配置******************************

frontend main *:5000  # 前端定义服务器名称和端口
acl url_static  path_beg -i /static /p_w_picpaths /javascript /stylesheets
acl url_static  path_end -i .jpg .gif .png .css .js
use_backend static     if url_static
default_backend       app
定义访问控制,如果符合 url_static,就代理到static,如果不是url_static,就使用默认的后端服务

***********************后端服务器配置*****************************

backend static
balance   roundrobin  #负载均衡调度算法
server   static 127.0.0.1:4331 check # 定义了一个后端服务器并做健康状况检测
backend app
balance   roundrobin
server app1 127.0.0.1:5001 check rise 2 fall 1
server app2 127.0.0.1:5002 check rise 2 fall 1
server app3 127.0.0.1:5003 check rise 2 fall 1
server app4 127.0.0.1:5004 check rise 2 fall 1
# check rise 2 fall 1 健康状况检查,rise表示后端realserver从stop到start检查的次数,fall表示从start到stop检查的次数



三、实例配置

本机ip172.16.5.16

开启forward转发功能

#sysctl-wnet.ipv4.ip_forward=1

关闭防火墙

为后端ip172.16.6.1做代理

为后端服务器提供页面并启动httpd

# vim /var/www/html/index.html
<h1>welcome!</>
# service httpd start
global
log     127.0.0.1 local2
chroot   /var/lib/haproxy
pidfile   /var/run/haproxy.pid
maxconn   4000
user    haproxy
group    haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/stats
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
mode          http
log           global
option         httplog
option         dontlognull
option http-server-close
option forwardfor    except 127.0.0.0/8 header X-Forward-For # 后端服务器日志中记录远程客户端ip,别忘了在后端服务器上修改log格式
option         redispatch
retries         3
timeout http-request  10s
timeout queue      1m
timeout connect     10s
timeout client     1m
timeout server     1m
timeout http-keep-alive 10s
timeout check      10s
maxconn         3000
#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend web
bind *:80
default_backend static
也可以写成
frontend web 172.16.5.16:80
dfault_backend static
#---------------------------------------------------------------------
# static backend for serving up p_w_picpaths, stylesheets and such
#---------------------------------------------------------------------
backend static
server   www.web1.com 172.16.6.1:80 check
stats          enable # 开启服务器状态信息
stats          hide-version # 隐藏版本信息
stats          realm haproxy\ stats # 说明认证信息 \ 转译了一个空格
stats          auth admin:admin # 认证用户
stats          admin if TRUE # 通过认证就允许管理
stats          uri /abc # 自定义stats显示页面uri

效果图


202150700.jpg


单独使用一个端口来监听stats状态信息。

global
log     127.0.0.1 local2
chroot   /var/lib/haproxy
pidfile   /var/run/haproxy.pid
maxconn   4000
user    haproxy
group    haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/stats
defaults
mode          http
log           global
option         httplog
option         dontlognull
option http-server-close
option forwardfor    except 127.0.0.0/8
option         redispatch
retries         3
timeout http-request  10s
timeout queue      1m
timeout connect     10s
timeout client     1m
timeout server     1m
timeout http-keep-alive 10s
timeout check      10s
maxconn         3000
listen stats
bind *:1080
stats          enable
stats          hide-version
stats          realm haproxy\ stats
stats          auth admin:admin
stats          admin if TRUE
stats          uri /abc
frontend web
bind *:80
default_backend static
backend static
server   www.web1.com 172.16.6.1:80 check


效果图:


202211132.jpg


202231438.jpg




四、负载均衡--调度算法


roundrobin动态支持权重和在服务器运行时调整,支持慢速启动

static-rr静态不支持在服务器运行时调整,不支持慢速启动

leastconn最少连接,只建议使用非常长的会话

source:后端服务器时动态服务器时使用,类似于nginx的iphash

Hash-type:map-based静态hash码取余计算iphash码除以所有的服务器数,余数得几就放在第几个服务器上

Hash-type:consistent动态一致性hashhash环

基于权重weight动态

uri根据用户访问的uri来负载均衡,它也有hash表,同样有hash-type,第一次访问的结果被负载到哪个服务器,保存在了hash表中,在来访问同样的uri,就会始终到这台服务器。

url_param根据用户帐号信息,将请求发往同一个服务器,同样有hash-type

hdr:首部根据请求首部调度,同样有hash-type

requestheader请求首部

reponseheader响应首部

hdrhosts)格式

hdrwww.a.com)实例



一致性hash负载均衡


global
log     127.0.0.1 local2
chroot   /var/lib/haproxy
pidfile   /var/run/haproxy.pid
maxconn   4000
user    haproxy
group    haproxy
daemon
stats socket /var/lib/haproxy/stats
defaults
mode          http
log           global
option         httplog
option         dontlognull
option http-server-close
option forwardfor    except 127.0.0.0/8
option         redispatch
retries         3
timeout http-request  10s
timeout queue      1m
timeout connect     10s
timeout client     1m
timeout server     1m
timeout http-keep-alive 10s
timeout check      10s
maxconn         3000
listen stats
bind *:1080
stats          enable
stats          hide-version
stats          realm haproxy\ stats
stats          auth admin:admin
stats          admin if TRUE
stats          uri /abc
frontend web
bind *:80
default_backend static
backend static
balance   source
hash-type  consistent
server   www.web1.com 172.16.6.1:80 check weight 3
server   www.web2.com 172.16.6.2:80 check weight 1




五、acl访问控制


frontend web
bind *:8080
default_backend static
acl abc src 172.16.5.100
redirect prefix http://172.16.5.16/def if abc

当客户端ip172.16.5.100时,重定向到http://172.16.5.16/def


acl要和redirectprefix或者redirectlocation搭配使用


官方实例,将用户登录后的url重定向到https安全连接。


acl clear   dst_port 80
acl secure   dst_port 8080
acl login_page url_beg  /login
acl logout   url_beg  /logout
acl uid_given url_reg  /login?userid=[^&]+
acl cookie_set hdr_sub(cookie) SEEN=1
redirect prefix  https://mysite.com set-cookie SEEN=1 if !cookie_set
redirect prefix  https://mysite.com      if login_page !secure
redirect prefix  http://mysite.com drop-query if login_page !uid_given
redirect location http://mysite.com/      if !login_page secure
redirect location / clear-cookie USERID=    if logout


访问阻止

frontend web
bind *:8080
default_backend static
acl abc src 172.16.5.100
block if abc  # 阻止访问


202300144.jpg


修改原配置文件,实现动静分离


frontend web
bind *:80
acl url_static    path_beg    -i /static /p_w_picpaths /javascript /stylesheets
#字符形式
acl url_static    path_reg    -i ^/static ^/p_w_picpaths ^/javascript ^/stylesheets
#正则表达式
acl url_static    path_end    -i .jpg .jpeg .gif .png .css .js
#字符
acl url_static    path_reg   -i .jpg $.jpeg$ .gif $.png$ .css$ .js$
# 正则表达式
#一般能用字符,就不要用正则表达式,字符的比正则表达式快。
use_backend static_servers     if url_static
default_backend dynamic_servers
backend static_servers
balance roundrobin
server imgsrv1 172.16.200.7:80 check maxconn 6000
server imgsrv2 172.16.200.8:80 check maxconn 6000
backend dynamic_servers
balance source
server websrv1 172.16.200.7:80 check maxconn 1000
server websrv2 172.16.200.8:80 check maxconn 1000
server websrv3 172.16.200.9:80 check maxconn 1000

haproxylisten配置示例:


listen webfarm
bind 192.168.0.99:80
mode http
stats enable
stats auth someuser:somepassword
balance roundrobin
cookie JSESSIONID prefix
option httpclose
option forwardfor
option httpchk HEAD /check.txt HTTP/1.0
server webA 192.168.0.102:80 cookie A check
server webB 192.168.0.103:80 cookie B check

Haproxy综合配置事例


global
pidfile /var/run/haproxy.pid
log 127.0.0.1 local0 info
defaults
mode http
clitimeout   600000
srvtimeout   600000
timeout connect 8000
stats enable
stats auth  admin:admin
stats uri/monitor
stats refresh5s
option httpchk GET /status
retries5
option redispatch
errorfile 503 /path/to/503.text.file
balanceroundrobin# each server is used in turns, according to assigned weight
frontend http
bind :80
monitor-uri  /haproxy # end point to monitor HAProxy status (returns 200)
acl api1 path_reg ^/api1/?
acl api2 path_reg ^/api2/?
use_backend api1 if api1
use_backend api2 if api2
backend api1
# option httpclose
server srv0 172.16.5.15:80 weight 1 maxconn 100 check inter 4000
server srv1 172.16.5.16:80 weight 1 maxconn 100 check inter 4000
server srv2 172.16.5.16:80 weight 1 maxconn 100 check inter 4000
backend api2
option httpclose
server srv01 172.16.5.18:80 weight 1 maxconn 50 check inter 4000



六、结合keepalived做高可用代理


拓扑图

163644368.jpg



规划:

准备工作请参照之前写的博客,无非就是时间同步,双机互信,主机名称能够互相解析。

node1:

ip:172.16.5.15

hostname:www.a.com

node2

ip:172.16.5.16

hostname:www.b.com

后端realserver让别人代做


配置haproxy

node1:# yum -y install haproxy
node2:# yum -y install haproxy
# cd /etc/haproxy
# mv haproxy.cfg haproxy.bak
# vim haproxy.cfg
global
log         127.0.0.1 local2
chroot      /var/lib/haproxy
pidfile     /var/run/haproxy.pid
maxconn     4000
user        haproxy
group       haproxy
daemon
stats socket /var/lib/haproxy/stats
defaults
mode                    http
log                     global
option                  httplog
option                  dontlognull
option http-server-close
option forwardfor       except 127.0.0.0/8 header X-Forward-For
option                  redispatch
retries                 3
timeout http-request    10s
timeout queue           1m
timeout connect         10s
timeout client          1m
timeout server          1m
timeout http-keep-alive 10s
timeout check           10s
maxconn                 3000
listen stats #专门弄个端口进行状态管理
bind *:1080
stats                   enable
stats                   hide-version
stats                   realm haproxy\ stats
stats                   auth admin:admin
stats                   admin if TRUE
stats                   uri /abc
frontend web
    bind *:80
    acl danymic path_end -i .php
    acl abc src 172.16.5.100
    block if abc
    use_backend php if danymic
    default_backend static
backend static
    balance     roundrobin
    server      www.web1.com 172.16.5.16:8080 check rise 2 fall 1 weight 1
    server      www.web2.com 172.16.5.15:8080 check rise 2 fall 1 weight 1
backend php
    balance roundrobin
    server    www.web3.com 172.16.6.1:80 check rise 2 fall 1 weight 1
    server    www.web4.com 172.16.6.2:80 check rise 2 fall 1 weight 1
# scp haproxy.cfg b:/etc/haproxy/

配置keepalived

node1

# yum -y install keepalived
# cd /etc/keepalived/
# vim keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_haproxy {
script "killall -0 haproxy"
interval 1
weight 2
}
#vrrp_script chk_mantaince_down {
#   script "[[ -f /etc/keepalived/down ]] && exit 1 || exit 0"
#   interval 1
#   weight 2
#}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 5
priority 99
advert_int 1
authentication {
auth_type PASS
auth_pass 11111
}
virtual_ipaddress {
172.16.5.100/16
}
track_script {
chk_mantaince_down
chk_haproxy
}
notify_master "/etc/keepalived/notify.sh master"
notify_backup "/etc/keepalived/notify.sh backup"
notify_fault "/etc/keepalived/notify.sh fault"
}
vrrp_instance VI_2 {
state MASTER
interface eth0
virtual_router_id 50
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 11111
}
virtual_ipaddress {
172.16.5.101/16
}
track_script {
chk_mantaince_down
chk_haproxy
}
notify_master "/etc/keepalived/notify.sh master"
notify_backup "/etc/keepalived/notify.sh backup"
notify_fault "/etc/keepalived/notify.sh fault"
}

该配置文件主要实现的功能:1、两个实例VI,实现了双主模型,主要为前端dns负载均衡使用;2、单个主从模型可以实现高可用,前提是若是针对某个服务,这个服务必须在keepalived启动之前启动,而且要对之监控;3、当然,也要做好对keepalived服务本身的监控,这就需要编辑另外的脚本,脚本所在的目录必须与notify_master"/etc/keepalived/notify.shmaster"中提到的一致。



编写对keepalived服务本身的监控脚本

# vim /etc/keepalived/notify.sh
#!/bin/bash
# Author: MageEdu <linuxedu@foxmail.com>
# description: An example of notify script
#
vip=172.16.5.100
contact='root@localhost'
Notify() {
mailsubject="`hostname` to be $1: $vip floating"
mailbody="`date '+%F %H:%M:%S'`: vrrp transition, `hostname` changed to be $1"
echo $mailbody | mail -s "$mailsubject" $contact
}
case "$1" in
master)
notify master
/etc/rc.d/init.d/haproxy start
exit 0
;;
backup)
notify backup
/etc/rc.d/init.d/haproxy restart
exit 0
;;
fault)
notify fault
exit 0
;;
*)
echo 'Usage: `basename $0` {master|backup|fault}'
exit 1
;;
esac


注意:本脚本中提到了vip,而本实验是双主模型,其中有两个vip,如果想省事,就写一个就行了,如果求精确,可以复制这个脚本,修改vip然后在配置文件中修改另一个实例中的notify.sh的路径。



node2中也要这样配置,不过要修改主从和优先级,这里不再罗嗦。

配置完之后,启动了haproxy和keepalived之后,对配置做下校验。


#service haproxy start
#service keepalived start
node1
# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 00:0c:29:a5:31:22 brd ff:ff:ff:ff:ff:ff
inet 172.16.5.15/16 brd 172.16.255.255 scope global eth0
inet 172.16.5.101/16 scope global secondary eth0
inet6 fe80::20c:29ff:fea5:3122/64 scope link
valid_lft forever preferred_lft forever
node2
# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 00:0c:29:cc:55:6d brd ff:ff:ff:ff:ff:ff
inet 172.16.5.16/16 brd 172.16.255.255 scope global eth0
inet 172.16.5.100/16 scope global secondary eth0
inet6 fe80::20c:29ff:fecc:556d/64 scope link
valid_lft forever preferred_lft forever

验证效果


###########################keepalived的双主模型实现的负载均衡##################################

152733243.jpg

152734210.jpg


############################动静分离之静态页面负载均衡############################

152854266.jpg

152855158.jpg


############################动静分离之动态页面负载均衡##############################

153011605.jpg

153012842.jpg


**************************************************************************************************访问专门设定的用于查看代理状态的页面

105548238.jpg


**************************************************************************************************修改配置文件,将拒绝访问的ip改为客户端ip,得到如下页面

frontendweb

bind*:80

default_backendstatic

aclabcsrc172.16.5.200

blockifabc

172.16.5.200是我物理机的IP地址

105549194.jpg

以上总结,有不足之处,望指教。。