24123r2 发表于 2016-12-30 10:23:43

haproxy做简单负载均衡

介绍:
HAProxy提供高可用性、负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费、快速并且可靠的一种解决方案。HAProxy特别适用于那些负载特大的web站点,这些站点通常又需要会话保持或七层处理。HAProxy运行在当前的硬件上,完全可以支持数以万计的并发连接。并且它的运行模式使得它可以很简单安全的整合进您当前的架构中,同时可以保护你的web服务器不被暴露到网络上.

配置文件:
haproxy 配置中分成五部分内容,分别如下:
1、global:参数是进程级的,通常是和操作系统相关。这些参数一般只设置一次,如果配置无误,就不需要再次进行修改
2、defaults:配置默认参数,这些参数可以被用到frontend,backend,Listen组件
3、frontend:接收请求的前端虚拟节点,Frontend可以更加规则直接指定具体使用后端的backend
4、backend:后端服务集群的配置,是真实服务器,一个Backend对应一个或者多个实体服务器
5、Listen: Fronted和backend的组合体
环境架构:

centos01 centos6.7eth0:10.0.0.223 eth1:192.168.122.242
centos03 centos6.7eth0:192.168.122.65
centos04 centos6.7eth0:192.168.122.207

当centos03或centos04的80端口down掉,就会把down掉的剔除,
当centos03或centos04的80端口up起来,就会把up起来的,添加

软件环境:

haproxy1.4.27
yum install gcc vim tree httpd -y
所有服务器关闭selinux
setenforce 0

1、centos03、centos04 安装httpd


1
2
3
4
yum install gcc vim tree httpd -y
service httpd start
#centos03添加一个index.html
echo "centos03" > /var/www/html/index.html




2、安装HAProxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
http://www.haproxy.org/ 官方网站
wget http://www.haproxy.org/download/1.4/src/haproxy-1.4.27.tar.gz
tar -zxf haproxy-1.4.27.tar.gz -C /usr/local/src/
cd /usr/local/src/haproxy-1.4.27/
makeTARGET=linux2628 ARCH=x86_64 PREFIX=/usr/local/haproxy   #将haproxy安装到/usr/local/haproxy,TARGET是指定内核版本
make install PREFIX=/usr/local/haproxy
cd /usr/local/haproxy/
# cd /usr/local/haproxy/
# ls
docsbinshare
# mkdir -p bin conf logs var/runvar/chroot
# tree
.
├── bin
├── conf
├── doc
│   └── haproxy
│       ├── architecture.txt
│       ├── configuration.txt
│       ├── haproxy-en.txt
│       └── haproxy-fr.txt
├── logs
├── sbin
│   └── haproxy
├── share
│   └── man
│       └── man1
│         └── haproxy.1
└── var
    ├── chroot
    └── run
#配置内核参数,开启转发功能
# vim /etc/sysctl.conf
net.ipv4.ip_forward = 1      #修改为1
# sysctl -p
net.ipv4.ip_forward = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296




3、创建haproxy用户

1
useraddhaproxy -s /sbin/nologin




4、修改配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# cp /usr/local/src/haproxy-1.4.27/examples/haproxy.cfg/usr/local/haproxy/conf/
vim/usr/local/haproxy/conf/haproxy.cfg
###########全局配置#########
global
    log 127.0.0.1   local0 #[日志输出配置,所有日志都记录在本机,通过local0输出]
    log 127.0.0.1   local1 notice#定义haproxy 日志级别
    daemon      #以后台形式运行harpoxy
    group haproxy
    user haproxy#以这个用户运行
    nbproc 1   #设置进程数量
    pidfile /usr/local/haproxy/var/run/haproxy.pid   #haproxy 进程PID文件
    ulimit-n 819200   #ulimit 的数量限制
    maxconn 20000    #默认最大连接数,需考虑ulimit-n限制
      #chroot /usr/share/haproxy #chroot运行路径
#    uid 99                  #运行haproxy 用户 UID
#      gid 99                  #运行haproxy 用户组gid
      #debug      #haproxy 调试级别,建议只在开启单进程的时候调试
      #quiet
   
########默认配置############
defaults
    log global
    mode http               #默认的模式mode { tcp|http|health },tcp是4层,http是7层,health只会返回OK
    optionhttplog         #日志类别,采用httplog
#    optiondontlognull   #不记录健康检查日志信息
#    retries 2               #两次连接失败就认为是服务器不可用,也可以通过后面设置
    optionforwardfor   #如果后端服务器需要获得客户端真实ip需要配置的参数,可以从Http Header中获得客户端ip
#    optionhttpclose    #每次请求完毕后主动关闭http通道,haproxy不支持keep-alive,只能模拟这种模式的实现
    option redispatch       #当serverId对应的服务器挂掉后,强制定向到其他健康的服务器
    option abortonclose   #当服务器负载很高的时候,自动结束掉当前队列处理比较久的链接
    maxconn 20000         #默认的最大连接数
    contimeout5000 #连接超时
    clitimeout50000#客户端超时
    srvtimeout 50000#服务器超时
      #timeout check 2000      #心跳检测超时
    #timeout http-keep-alive10s   #默认持久连接超时时间
    #timeout http-request   10s   #默认http请求超时时间
      #timeoutqueue          1m   #默认队列超时时间
    balance roundrobin    #设置默认负载均衡方式,轮询方式
      #balance source      # 设置默认负载均衡方式,类似于nginx的ip_hash
      #balnace leastconn   #设置默认负载均衡方式,最小连接数
   
########统计页面配置########
listen admin_stats
      bind 0.0.0.0:1080               #设置Frontend和Backend的组合体,监控组的名称,按需要自定义名称
      mode http                     #http的7层模式
      option httplog                  #采用http日志格式
      #log 127.0.0.1 local0 err       #错误日志记录
      maxconn 10                      #默认的最大连接数
      stats refresh 30s               #统计页面自动刷新时间
      stats uri /stats                #统计页面url
      stats realm XingCloud\ Haproxy#统计页面密码框上提示文本
      stats auth admin:admin   #设置监控页面的用户和密码:admin,可以设置多个用户名
      stats authyanconggod:123456   #设置监控页面的用户和密码:123456
      stats hide-version            #隐藏统计页面上HAProxy的版本信息
      statsadmin if TRUE       #设置手工启动/禁用,后端服务器(haproxy-1.4.9以后版本)
         
########设置haproxy 错误页面#####
#errorfile 403/usr/local/haproxy/errorfiles/403.http
#errorfile 500 /usr/local/haproxy/errorfiles/500.http
#errorfile 502 /usr/local/haproxy/errorfiles/502.http
#errorfile 503 /usr/local/haproxy/errorfiles/503.http
#errorfile 504 /usr/local/haproxy/errorfiles/504.http
   
########frontend前端配置##############
#bind *:80
    #这里建议使用bind *:80的方式,要不然做集群高可用的时候有问题,vip切换到其他机器就不能访问了。
   # acl web hdr(host) -i www.abc.com
    #acl后面是规则名称,-i是要访问的域名,
   # acl img hdr(host) -i img.abc.com
   # 如果访问www.abc.com这个域名就分发到下面的webserver 的作用域。
    #如果访问img.abc.com.cn就分发到imgserver这个作用域。
   # use_backend webserver if web
   # use_backend imgserver if img
      
########backend后端配置##############
#backend webserver             #webserver作用域
#    mode http
#    balance   roundrobin      
    #banlance roundrobin 轮询,balance source 保存session值,支持static-rr,leastconn,first,uri等参数
#    optionhttpchk /index.html HTTP/1.0#健康检查
    #检测文件,如果分发到后台index.html访问不到就不再分发给它
#    serverweb1 10.16.0.9:8085 cookie 1 weight 5 check inter 2000 rise 2 fall 3
#    serverweb2 10.16.0.10:8085 cookie 2 weight 3 check inter 2000 rise 2 fall 3
    #cookie 1表示serverid为1,check inter 1500 是检测心跳频率   
    #rise 2是2次正确认为服务器可用,fall 3是3次失败认为服务器不可用,weight代表权重
#backend imgserver
#    mode http
#    optionhttpchk /index.php
#    balance   roundrobin                           
#    server      img01 192.168.137.101:80check inter 2000 fall 3
#    server      img02 192.168.137.102:80check inter 2000 fall 3
      
########tcp配置#################
#listen test1
#      bind 0.0.0.0:90
#      mode tcp
#    optiontcplog          #日志类别,采用tcplog
#      maxconn 4086
      #log 127.0.0.1 local0 debug
#      server s1 10.18.138.201:80weight 1
#      server s2 10.18.102.190:80weight 1
listen my_first_haproxy
      bind 0.0.0.0:80
      mode http
      stats enable
      stats hide-version
      stats uri /manage?status
      stats auth admin:admin
      balance roundrobin
      option httpclose
      option forwardfor
      cookie SERVERID insert indirect
      timeout server 15s
      timeout connect 15s
      server centos03 192.168.122.65:80 check port 80 inter 5000 fall 5
      server centos04 192.168.122.207:80 check port 80 inter 5000 fall 5




5、测试配置文件是否正常

1
2
3
4
5
6
# pwd
/usr/local/haproxy
# ls
binconfdoclogssbinsharevar
# ./sbin/haproxy -f ./conf/haproxy.cfg-c
Configuration file is valid




6、添加日志支持
对应好配置文件的local0和local1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# cat /etc/rsyslog.conf   
# rsyslog v5 configuration file

# For more information see /usr/share/doc/rsyslog-*/rsyslog_conf.html
# If you experience problems, see http://www.rsyslog.com/doc/troubleshoot.html

#### MODULES ####

$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imklog   # provides kernel logging support (previously done by rklogd)
#$ModLoad immark# provides --MARK-- message capability

# Provides UDP syslog reception
$ModLoad imudp                     #去掉这个注释
$UDPServerRun 514                        #去掉这个注释

# Provides TCP syslog reception
#$ModLoad imtcp
#$InputTCPServerRun 514


#### GLOBAL DIRECTIVES ####

# Use default timestamp format
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

# File syncing capability is disabled by default. This feature is usually not required,
# not useful and an extreme performance hit
#$ActionFileEnableSync on

# Include all config files in /etc/rsyslog.d/
$IncludeConfig /etc/rsyslog.d/*.conf


#### RULES ####

# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.*                                                 /dev/console

# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none                /var/log/messages

# The authpriv file has restricted access.
authpriv.*                                              /var/log/secure

# Log all the mail messages in one place.
mail.*                                                -/var/log/maillog


# Log cron stuff
cron.*                                                /var/log/cron

# Everybody gets emergency messages
*.emerg                                                 *

# Save news errors of level crit and higher in a special file.
uucp,news.crit                                          /var/log/spooler

# Save boot messages also to boot.log
local7.*                                                /var/log/boot.log


# ### begin forwarding rule ###
# The statement between the begin ... end define a SINGLE forwarding
# rule. They belong together, do NOT split them. If you create multiple
# forwarding rules, duplicate the whole block!
# Remote Logging (we use TCP for reliable delivery)
#
# An on-disk queue is created for this action. If the remote host is
# down, messages are spooled to disk and sent when it is up again.
#$WorkDirectory /var/lib/rsyslog # where to place spool files
#$ActionQueueFileName fwdRule1 # unique name prefix for spool files
#$ActionQueueMaxDiskSpace 1g   # 1gb space limit (use as much as possible)
#$ActionQueueSaveOnShutdown on # save messages to disk on shutdown
#$ActionQueueType LinkedList   # run asynchronously
#$ActionResumeRetryCount -1    # infinite retries if host is down
# remote host is: name/ip:port, e.g. 192.168.0.1:514, port optional
#*.* @@remote-host:514
# ### end of the forwarding rule ###

#添加下面这两行
local0.* /usr/local/haproxy/logs/haproxy_all.log
local1.* /usr/local/haproxy/logs/haproxy_notice.log





1
2
3
4
5
6
7
再修改rsyslog为下面的内容
# cat /etc/sysconfig/rsyslog
# Options for rsyslogd
# Syslogd options are deprecated since rsyslog v3.
# If you want to use them, switch to compatibility mode 2 by "-c 2"
# See rsyslogd(8) for more details
SYSLOGD_OPTIONS="-c 2 -m 0 -r -x"





1
2
3
4
5
/etc/init.d/rsyslog restart
#查看rsyslogd端口
# netstat -lntup|grep 514
udp      0      0 0.0.0.0:514               0.0.0.0:*                               5875/rsyslogd      
udp      0      0 :::514                      :::*                                    5875/rsyslogd




7、启动服务


1
./sbin/haproxy -f ./conf/haproxy.cfg-D      #后台形式运行




8、查看日志


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# pwd
/usr/local/haproxy
# ls logs/
haproxy_all.loghaproxy_notice.log
# tail -f logs/haproxy_all.log
Dec 29 05:42:32 127.0.0.1 haproxy: 10.0.0.196:4558 my_first_haproxy my_first_haproxy/centos03 8744/0/1/2/8750 200 274 - - --NI 1/1/0/0/0 0/0 "GET / HTTP/1.1"
Dec 29 05:42:32 127.0.0.1 haproxy: 10.0.0.196:4559 my_first_haproxy my_first_haproxy/centos04 9019/0/2/2/9025 404 465 - - --NI 0/0/0/0/0 0/0 "GET /favicon.ico HTTP/1.1"
Dec 29 05:42:33 127.0.0.1 haproxy: 10.0.0.196:4622 my_first_haproxy my_first_haproxy/<NOSRV> -1/-1/-1/-1/4 401 262 - - PRNN 0/0/0/0/0 0/0 "GET /manage?status HTTP/1.1"
Dec 29 05:43:26 127.0.0.1 haproxy: 10.0.0.196:5211 my_first_haproxy my_first_haproxy/centos03 5/0/4/2/15 304 148 - - --NI 2/2/0/0/0 0/0 "GET / HTTP/1.1"
Dec 29 05:43:28 127.0.0.1 haproxy: 10.0.0.196:5212 my_first_haproxy my_first_haproxy/centos04 1941/0/3/4/1952 403 5159 - - --NI 1/1/0/0/0 0/0 "GET / HTTP/1.1"
Dec 29 05:43:28 127.0.0.1 haproxy: 10.0.0.196:5213 my_first_haproxy my_first_haproxy/centos03 1997/0/5/3/2011 200 2581 - - --NI 1/1/1/0/0 0/0 "GET /icons/apache_pb.gif HTTP/1.1"
Dec 29 05:43:28 127.0.0.1 haproxy: 10.0.0.196:5242 my_first_haproxy my_first_haproxy/centos04 0/0/6/8/145 200 4211 - - --NI 0/0/0/0/0 0/0 "GET /icons/poweredby.png HTTP/1.1"
Dec 29 05:43:29 127.0.0.1 haproxy: 10.0.0.196:5251 my_first_haproxy my_first_haproxy/centos03 0/0/3/3/12 200 274 - - --NI 1/1/0/0/0 0/0 "GET / HTTP/1.1"
Dec 29 05:43:29 127.0.0.1 haproxy: 10.0.0.196:5252 my_first_haproxy my_first_haproxy/centos04 486/0/4/4/500 403 5159 - - --NI 1/1/0/0/0 0/0 "GET / HTTP/1.1"
Dec 29 05:43:33 127.0.0.1 haproxy: 10.0.0.196:5253 my_first_haproxy my_first_haproxy/<STATS> 3702/-1/-1/-1/3711 200 11077 - - PRNN 0/0/0/0/0 0/0 "GET /manage?status HTTP/1.1"




9、登录监控页面
我特意设置了两个监控管理的入口,一个有xing cloud 提示,这个比较安全点。
监控管理
http://10.0.0.233:1080/stats
http://10.0.0.233/manage?status
访问10.0.0.233 会自动轮询切换网页










10、启动脚本

暂时未修改好


总结:
Ngnix:Ngnix:
1、工作在网络的7层之上,可以针对http应用做一些分流的策略,比如针对域名、目录结构;
2、Nginx对网络的依赖比较小,理论上能ping通就就能进行负载功能;
3、Nginx安装和配置比较简单,测试起来比较方便;
4、也可以承担高的负载压力且稳定,一般能支撑超过1万次的并发;
5、对后端服务器的健康检查,只支持通过端口来检测,不支持通过url来检测。
6、Nginx对请求的异步处理可以帮助节点服务器减轻负载;
7、Nginx仅能支持http、https和Email协议,这样就在适用范围较小。
8、不支持Session的直接保持,但能通过ip_hash来解决。、对Big request header的支持不是很好,
9、支持负载均衡算法:Round-robin(轮循)、Weight-round-robin(带权轮循)、Ip-hash(Ip哈希)
10、Nginx还能做Web服务器即Cache功能。
HAProxy的特点是:
1、支持两种代理模式:TCP(四层)和HTTP(七层),支持虚拟主机;
2、能够补充Nginx的一些缺点比如Session的保持,Cookie的引导等工作
3、支持url检测后端的服务器出问题的检测会有很好的帮助。
4、更多的负载均衡策略比如:动态加权轮循(Dynamic Round Robin),加权源地址哈希(Weighted Source Hash),加权URL哈希和加权参数哈希(Weighted Parameter Hash)已经实现
5、单纯从效率上来讲HAProxy更会比Nginx有更出色的负载均衡速度。
6、HAProxy可以对Mysql进行负载均衡,对后端的DB节点进行检测和负载均衡。
9、支持负载均衡算法:Round-robin(轮循)、Weight-round-robin(带权轮循)、source(原地址保持)、RI(请求URL)、rdp-cookie(根据cookie)
10、不能做Web服务器即Cache。


页: [1]
查看完整版本: haproxy做简单负载均衡