haproxy负载均衡服务器

简介

HAProxy是一个tcp/http反向代理,它特别适合于高
可用性环境。事实上,它可以:
——根据静态分配的cookie路由HTTP请求
——在多个服务器之间传播负载,并确保服务器持久性
通过使用HTTP cookie
——在主服务器失败的情况下切换到备份服务器
:接受连接到专用端口的连接,用于服务监视
——停止接受连接而不破坏已有的连接
——在两个方向上添加、修改和删除HTTP头信息
——块请求匹配特定的模式
——向来自URI的经过身份验证的用户报告详细状态
下面简单配置一个haproxy服务器

[root@localhost haproxy]# vim haproxy.cfg 
#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    local2.*                       /var/log/haproxy.log
    #
    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
    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  chenxi
bin *:80  #定义客户端访问的端口
default_backend   webchenxi #定义调度到的组
backend webchenxi  #定义组内的信息
balance  roundrobin    #定义调度算法  roundrobin表示轮巡也表示加权轮巡因为
server CX1 172.16.251.61:80 check    #定义组内的主机;并做健康检测
server CX2 172.16.254.74:8o check   #定义组内的主机;并做健康检测
#frontend  main *:5000
#    acl url_static       path_beg       -i /static /images /javascript /stylesheets

#    acl url_static       path_end       -i .jpg .gif .png .css .js

#   use_backend static          if url_static
#    default_backend             app

#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
#backend static
#   balance     roundrobin
#    server      static 127.0.0.1:4331 check

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
#backend app
#    balance     roundrobin
#    server  app1 127.0.0.1:5001 check
#    server  app2 127.0.0.1:5002 check
#    server  app3 127.0.0.1:5003 check
#    server  app4 127.0.0.1:5004 check
保存退出

配置日志服务

# rsyslog 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 ####

# The imjournal module bellow is now used as a message source instead of imuxsock.
$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imjournal # provides access to the systemd journal
#$ModLoad imklog # reads kernel messages (the same are read from journald)
#$ModLoad immark  # provides --MARK-- message capability

# Provides UDP syslog reception
$ModLoad imudp   注释去掉启用
$UDPServerRun 514  注释去掉启用

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


#### GLOBAL DIRECTIVES ####

# Where to place auxiliary files
$WorkDirectory /var/lib/rsyslog

# 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

# Turn off message reception via local log socket;
# local messages are retrieved through imjournal now.
$OmitLocalLogging on

# File to store the position in the journal
$IMJournalStateFile imjournal.state


#### 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                                                 :omusrmsg:*

# 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
local2.*                        /var/log/haproxy.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.
#$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 ###
保存退出后重启日志服务
[root@localhost haproxy]# systemctl restart rsyslog.service 

启动服务
systemctl start haproxy.service

[root@localhost haproxy]# ss -lnt
State       Recv-Q Send-Q               Local Address:Port                              Peer Address:Port              
LISTEN      0      128                              *:80                                           *:*                  
LISTEN      0      128                              *:22                                           *:*                  
LISTEN      0      100                      127.0.0.1:25                                           *:*                  
LISTEN      0      10                       127.0.0.1:6082                                         *:*                  
LISTEN      0      128                             :::80                                          :::*                  
LISTEN      0      128                             :::22                                          :::*                  
LISTEN      0      100                            ::1:25                                          :::*                   

客户端测试

[root@root ~]# curl 172.16.253.147

chenxi r2

[root@root ~]# curl 172.16.253.147

chenxi1

[root@root ~]# curl 172.16.253.147

chenxi r2

[root@root ~]# curl 172.16.253.147

chenxi1

[root@root ~]# curl 172.16.253.147

chenxi r2

使用下一个调度方法

#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    local2.*                       /var/log/haproxy.log
    #
    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
    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  chenxi
bind *:80  #定义客户端访问的端口
default_backend   webchenxi #定义调度到的组
backend webchenxi  #定义组内的信息
balance  first    #定义调度算法次此算法是当多台主机存在
server CX1 172.16.251.61:80 check maxconn 3   #定义组内的主机;并做健康检测  定义maxconn的并发连接数
server CX2 172.16.254.74:80 check   #定义组内的主机;并做健康检测
#frontend  main *:5000
#    acl url_static       path_beg       -i /static /images /javascript /stylesheets

#    acl url_static       path_end       -i .jpg .gif .png .css .js

#   use_backend static          if url_static
#    default_backend             app

#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
#backend static
#   balance     roundrobin
#    server      static 127.0.0.1:4331 check

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
#backend app
#    balance     roundrobin
#    server  app1 127.0.0.1:5001 check
#    server  app2 127.0.0.1:5002 check
#    server  app3 127.0.0.1:5003 check
#    server  app4 127.0.0.1:5004 check
客户端测试
[root@root ~]# ab -c 10 -n 1000 http://172.16.253.147/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 172.16.253.147 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:        Apache/2.2.15
Server Hostname:        172.16.253.147
Server Port:            80

Document Path:          /
Document Length:        17 bytes

Concurrency Level:      10
Time taken for tests:   1.029 seconds
Complete requests:      1000
Failed requests:        515
   (Connect: 0, Receive: 0, Length: 515, Exceptions: 0)
Write errors:           0
Total transferred:      286060 bytes
HTML transferred:       19060 bytes
Requests per second:    972.22 [#/sec] (mean)
Time per request:       10.286 [ms] (mean)
Time per request:       1.029 [ms] (mean, across all concurrent requests)
Transfer rate:          271.59 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    2   4.6      1      62
Processing:     1    8   7.3      5      75
Waiting:        1    7   6.8      5      72
Total:          2   10   9.4      7     101

Percentage of the requests served within a certain time (ms)
  50%      7
  66%      9
  75%     11
  80%     14
  90%     19
  95%     25
  98%     35
  99%     47
 100%    101 (longest request)
后端1 的测试日志结果
[root@chenxiyue ~]# tail /var/log/httpd/access_log
172.16.253.147 - - [28/Aug/2017:18:20:49 +0800] "GET / HTTP/1.0" 200 17 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:49 +0800] "GET / HTTP/1.0" 200 17 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:49 +0800] "GET / HTTP/1.0" 200 17 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:49 +0800] "GET / HTTP/1.0" 200 17 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:49 +0800] "GET / HTTP/1.0" 200 17 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:49 +0800] "GET / HTTP/1.0" 200 17 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:49 +0800] "GET / HTTP/1.0" 200 17 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:49 +0800] "GET / HTTP/1.0" 200 17 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:49 +0800] "GET / HTTP/1.0" 200 17 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:49 +0800] "GET / HTTP/1.0" 200 17 "-" "ApacheBench/2.3"
后端2 测试后日志结果
[root@chenxi ~]# tail /var/log/httpd/access_log 
172.16.253.147 - - [28/Aug/2017:18:20:50 +0800] "GET / HTTP/1.0" 200 21 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:50 +0800] "GET / HTTP/1.0" 200 21 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:50 +0800] "GET / HTTP/1.0" 200 21 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:50 +0800] "GET / HTTP/1.0" 200 21 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:50 +0800] "GET / HTTP/1.0" 200 21 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:50 +0800] "GET / HTTP/1.0" 200 21 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:50 +0800] "GET / HTTP/1.0" 200 21 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:50 +0800] "GET / HTTP/1.0" 200 21 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:50 +0800] "GET / HTTP/1.0" 200 21 "-" "ApacheBench/2.3"
172.16.253.147 - - [28/Aug/2017:18:20:50 +0800] "GET / HTTP/1.0" 200 21 "-" "ApacheBench/2.3"

另一种算法的设置

#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    local2.*                       /var/log/haproxy.log
    #
    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
    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  chenxi
bind *:80  #定义客户端访问的端口
default_backend   webchenxi #定义调度到的组
backend webchenxi  #定义组内的信息
balance  uri    #定义调度算法 Uri  目标
server CX1 172.16.251.61:80 check maxconn 3   #定义组内的主机;并做健康检测
server CX2 172.16.254.74:80 check   #定义组内的主机;并做健康检测
hash-type consistent   对URI最目标目标地址哈希
#frontend  main *:5000
#    acl url_static       path_beg       -i /static /images /javascript /stylesheets

#    acl url_static       path_end       -i .jpg .gif .png .css .js

#   use_backend static          if url_static
#    default_backend             app

#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
#backend static
#   balance     roundrobin
#    server      static 127.0.0.1:4331 check

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
#backend app
#    balance     roundrobin
#    server  app1 127.0.0.1:5001 check
#    server  app2 127.0.0.1:5002 check
#    server  app3 127.0.0.1:5003 check
#    server  app4 127.0.0.1:5004 check
[root@localhost haproxy]# systemctl reload haproxy.service  重启服务
r1的设置
[root@chenxiyue ~]# cd /var/www/html/
[root@chenxiyue html]# mkdir chenxidy
[root@chenxiyue html]# echo "r1serve" > chenxidy/index.html
[root@chenxiyue html]# cat index.html 

chenxi1

[root@chenxiyue html]# cat chenxidy/index.html r1serve r2 的相关设置 [root@chenxi ~]# cd /var/www/html/ [root@chenxi html]# mkdir chenxidy [root@chenxi html]# echo "server 2" chenxidy/index.html server 2 chenxidy/index.html [root@chenxi html]# echo "server 2" > chenxidy/index.html 客户端测试 [root@root ~]# curl 172.16.253.147/chenxidy/index.html r1serve [root@root ~]# curl 172.16.253.147/chenxidy/index.html r1serve [root@root ~]# curl 172.16.253.147/chenxidy/index.html r1serve [root@root ~]# curl 172.16.253.147/chenxidy/index.html r1serve [root@root ~]# curl 172.16.253.147/chenxidy/index.html r1serve [root@root ~]# curl 172.16.253.147/chenxidy/index.html r1serve [root@root ~]# curl 172.16.253.147/chenxidy/index.html r1serve [root@root ~]# curl 172.16.253.147/chenxidy/index.html r1serve

浏览器只要相同的就发给同一台主机 ;启用压缩

#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    local2.*                       /var/log/haproxy.log
    #
    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
    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  chenxi
bind *:80
compression algo gzip
compression type text/html text/plain application/xml application/javascript
default_backend   webchenxi 
backend webchenxi  
balance  hdr(User-Agent) 
server CX1 172.16.251.61:80 check maxconn 3
server CX2 172.16.254.74:80 check
hash-type consistent
#frontend  main *:5000
#    acl url_static       path_beg       -i /static /images /javascript /stylesheets

#    acl url_static       path_end       -i .jpg .gif .png .css .js

#   use_backend static          if url_static
#    default_backend             app

#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
#backend static
#   balance     roundrobin
#    server      static 127.0.0.1:4331 check

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
#backend app
#    balance     roundrobin
#    server  app1 127.0.0.1:5001 check
#    server  app2 127.0.0.1:5002 check
#    server  app3 127.0.0.1:5003 check
#    server  app4 127.0.0.1:5004 check

你可能感兴趣的:(haproxy负载均衡服务器)