• Haproxy解析


    简单介绍

    HAProxy是一款提供高可用性、负载均衡以及基于TCP和HTTP应用的代理软件,HAProxy是全然免费的、借助HAProxy能够高速而且可靠的提供基于TCP和HTTP应用的代理解决方式。HAProxy适用于那些负载较大的web网站,这些网站通常又须要会话保持或七层处理。 HAProxy能够支持数以万计的并发连接,而且HAProxy的执行模式使得它能够非常easy安全的整合进架构中,同一时候能够保护webserver不被暴露到网络上。

     

    安装与管理

    1)         安装步骤參考例如以下,将软件上传到/opt目录下

    cd /opt
    tar zxvf haproxy-1.4.9.tar.gz   
    cd haproxy-1.4.9

    make TARGET=linux26 PREFIX=/opt

    make install PREFIX=/opt  

    2)         Haproxy管理

    若haproxy已经配置完成,參考例如以下命令,启动

    cd /opt/haproxy/sbin

    ./haproxy -f haproxy.cfg

    输入usernamepassword,在例如以下页面进行状态监控

    http://x.x.x.x:1080/haproxy-stats

    加入开机自启服务。将haproxy启动命令加入到/etc/rc.local文件里。如

    /opt/haproxy/sbin/haproxy -f haproxy.cfg

     

     

    配置优化

    1)         Haproxy配置优化说明

    參数配置演示样例

    规则说明

    maxconn 32768

    最大连接数

    daemon

    推荐使用守护进程模式启动

    nbproc 8

    负载均衡的并发进程数

    retries 3

    重试次数

     

     

    2)         Haproxy配置(haproxy.cfg)演示样例

    创建配置文件

    cd  /opt/haproxy

    touch  haproxy.cfg

    配置演示样例

    global   

            log 127.0.0.1    local0

            maxconn 4096   

            chroot /opt/haproxy   

    #      uid www   

    #      gid www

    uid  0

           gid  0

            daemon   

            nbproc 2 

            pidfile logs/haproxy.pid   

            #debug   

            #quiet   

    defaults   

            log     127.0.0.1       local3   

            mode    http   

            option  httplog   

            option  httpclose   

            option  dontlognull   

            option  forwardfor   

            option  redispatch   

            retries 2   

            maxconn 2000   

            balance roundrobin   

    stats enable

            stats   uri     /haproxy-stats   

            contimeout      5000   

            clitimeout      50000   

            srvtimeout      50000   

    listen  web_proxy 0.0.0.0:1080   

            option  httpchk GET /ping.jsp   

            server  s1 192.168.15.110:8080 weight 3 check   

            server  s3 192.168.15.111:8080 weight 3 check

    listen  mysql_proxy 0.0.0.0:3306

            server  s1 192.168.15.110:3306 weight 3 check   

            server  s3 192.168.15.111:3306 weight 3 check

     



    写在前面的话。《Haproxy配置文件具体解释》文档部分信息来自网络,同一时候參考过官方的架构指南,在此很感谢zero提供的文档。以及在学习Haproxy过程中的帮助。

    1. #/usr/local/sbin/haproxy -f /etc/haproxy/haproxy.cfg -st `cat /var/run/haproxy.pid` 
    2.        ####################全局配置信息######################## 
    3.        #######參数是进程级的,通常和操作系统(OS)相关######### 
    4. global 
    5.        maxconn 20480                   #默认最大连接数 
    6.        log 127.0.0.1 local3            #[err warning info debug] 
    7.        chroot /var/haproxy             #chroot执行的路径 
    8.        uid 99                          #所属执行的用户uid 
    9.        gid 99                          #所属执行的用户组 
    10.        daemon                          #以后台形式执行haproxy 
    11.        nbproc 1                        #进程数量(能够设置多个进程提高性能) 
    12.        pidfile /var/run/haproxy.pid    #haproxy的pid存放路径,启动进程的用户必须有权限訪问此文件 
    13.        ulimit-n 65535                  #ulimit的数量限制 
    14.  
    15.  
    16.        #####################默认的全局设置###################### 
    17.        ##这些參数能够被利用配置到frontend,backend,listen组件## 
    18. defaults 
    19.        log global 
    20.        mode http                       #所处理的类别 (#7层 http;4层tcp  ) 
    21.        maxconn 20480                   #最大连接数 
    22.        option httplog                  #日志类别http日志格式 
    23.        option httpclose                #每次请求完成后主动关闭http通道 
    24.        option dontlognull              #不记录健康检查的日志信息 
    25.        option forwardfor               #假设后端服务器须要获得client真实ip须要配置的參数,能够从Http Header中获得clientip  
    26.        option redispatch               #serverId相应的服务器挂掉后,强制定向到其它健康的服务器  
    27.        option abortonclose             #当服务器负载非常高的时候,自己主动结束掉当前队列处理比較久的连接 
    28.        stats refresh 30                #统计页面刷新间隔 
    29.        retries 3                       #3次连接失败就觉得服务不可用,也能够通过后面设置 
    30.        balance roundrobin              #默认的负载均衡的方式,轮询方式 
    31.       #balance source                  #默认的负载均衡的方式,类似nginx的ip_hash 
    32.       #balance leastconn               #默认的负载均衡的方式,最小连接 
    33.        contimeout 5000                 #连接超时 
    34.        clitimeout 50000                #client超时 
    35.        srvtimeout 50000                #服务器超时 
    36.        timeout check 2000              #心跳检測超时 
    37.  
    38.        ####################监控页面的设置####################### 
    39. listen admin_status                    #Frontend和Backend的组合体,监控组的名称,按需自己定义名称 
    40.         bind 0.0.0.0:65532             #监听port 
    41.         mode http                      #http的7层模式 
    42.         log 127.0.0.1 local3 err       #错误日志记录 
    43.         stats refresh 5s               #每隔5秒自己主动刷新监控页面 
    44.         stats uri /admin?stats         #监控页面的url 
    45.         stats realm itnihao itnihao   #监控页面的提示信息 
    46.         stats auth admin:admin         #监控页面的用户和passwordadmin,能够设置多个username 
    47.         stats auth admin1:admin1       #监控页面的用户和passwordadmin1 
    48.         stats hide-version             #隐藏统计页面上的HAproxy版本号信息  
    49.         stats admin if TRUE            #手工启用/禁用,后端服务器(haproxy-1.4.9以后版本号) 
    50.  
    51.  
    52.        errorfile 403 /etc/haproxy/errorfiles/403.http 
    53.        errorfile 500 /etc/haproxy/errorfiles/500.http 
    54.        errorfile 502 /etc/haproxy/errorfiles/502.http 
    55.        errorfile 503 /etc/haproxy/errorfiles/503.http 
    56.        errorfile 504 /etc/haproxy/errorfiles/504.http 
    57.  
    58.        #################HAProxy的日志记录内容设置################### 
    59.        capture request  header Host           len 40 
    60.        capture request  header Content-Length len 10 
    61.        capture request  header Referer        len 200 
    62.        capture response header Server         len 40 
    63.        capture response header Content-Length len 10 
    64.        capture response header Cache-Control  len 8 
    65.      
    66.        #######################站点监測listen配置##################### 
    67.        ###########此使用方法主要是监控haproxy后端服务器的监控状态############ 
    68. listen site_status 
    69.        bind 0.0.0.0:1081                    #监听port 
    70.        mode http                            #http的7层模式 
    71.        log 127.0.0.1 local3 err             #[err warning info debug] 
    72.        monitor-uri /site_status             #站点健康检測URL,用来检測HAProxy管理的站点能否够用。正常返回200,不正常返回503 
    73.        acl site_dead nbsrv(server_web) lt 2 #定义站点down时的策略当挂在负载均衡上的指定backend的中有效机器数小于1台时返回true 
    74.        acl site_dead nbsrv(server_blog) lt 2 
    75.        acl site_dead nbsrv(server_bbs)  lt 2  
    76.        monitor fail if site_dead            #当满足策略的时候返回503,网上文档说的是500。实际測试为503 
    77.        monitor-net 192.168.16.2/32          #来自192.168.16.2的日志信息不会被记录和转发 
    78.        monitor-net 192.168.16.3/32 
    79.  
    80.        ########frontend配置############ 
    81.        #####注意,frontend配置里面能够定义多个acl进行匹配操作######## 
    82. frontend http_80_in 
    83.        bind 0.0.0.0:80      #监听port。即haproxy提供web服务的port,和lvs的vipport类似 
    84.        mode http            #http的7层模式 
    85.        log global           #应用全局的日志配置 
    86.        option httplog       #启用http的log 
    87.        option httpclose     #每次请求完成后主动关闭http通道,HA-Proxy不支持keep-alive模式 
    88.        option forwardfor    #假设后端服务器须要获得client的真实IP须要配置次參数。将能够从Http Header中获得clientIP 
    89.        ########acl策略配置############# 
    90.        acl itnihao_web hdr_reg(host) -i ^(www.itnihao.cn|ww1.itnihao.cn)$    
    91.        #假设请求的域名满足正則表達式中的2个域名返回true -i是忽略大写和小写 
    92.        acl itnihao_blog hdr_dom(host) -i blog.itnihao.cn 
    93.        #假设请求的域名满足www.itnihao.cn返回true -i是忽略大写和小写 
    94.        #acl itnihao    hdr(host) -i itnihao.cn 
    95.        #假设请求的域名满足itnihao.cn返回true -i是忽略大写和小写 
    96.        #acl file_req url_sub -i  killall
    97.        #在请求url中包括killall=,则此控制策略返回true,否则为false 
    98.        #acl dir_req url_dir -i allow 
    99.        #在请求url中存在allow作为部分地址路径,则此控制策略返回true,否则返回false 
    100.        #acl missing_cl hdr_cnt(Content-length) eq 0 
    101.        #当请求的header中Content-length等于0时返回true 
    102.  
    103.        ########acl策略匹配相应############# 
    104.        #block if missing_cl 
    105.        #当请求中header中Content-length等于0阻止请求返回403 
    106.        #block if !file_req || dir_req 
    107.        #block表示阻止请求,返回403错误,当前表示假设不满足策略file_req,或者满足策略dir_req,则阻止请求 
    108.        use_backend  server_web  if itnihao_web 
    109.        #当满足itnihao_web的策略时使用server_web的backend 
    110.        use_backend  server_blog if itnihao_blog 
    111.        #当满足itnihao_blog的策略时使用server_blog的backend 
    112.        #redirect prefix http://blog.itniaho.cn code 301 if itnihao 
    113.        #当訪问itnihao.cn的时候,用http的301挑转到http://192.168.16.3 
    114.        default_backend server_bbs 
    115.        #以上都不满足的时候使用默认server_bbs的backend 
    116.  
    117.  
    118.  
    119.  
    120.        ##########backend的设置############## 
    121.        #以下我将设置三组服务器 server_web,server_blog。server_bbs
    122. ###########################backend server_web############################# 
    123. backend server_web 
    124.        mode http            #http的7层模式 
    125.        balance roundrobin   #负载均衡的方式,roundrobin平均方式 
    126.        cookie SERVERID      #同意插入serverid到cookie中,serverid后面能够定义 
    127.        option httpchk GET /index.html #心跳检測的文件 
    128.        server web1 192.168.16.2:80 cookie web1 check inter 1500 rise 3 fall 3 weight 1  
    129.        #服务器定义,cookie 1表示serverid为web1,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用。 
    130.        #fall 3是3次失败觉得服务器不可用。weight代表权重 
    131.        server web2 192.168.16.3:80 cookie web2 check inter 1500 rise 3 fall 3 weight 2 
    132.        #服务器定义。cookie 1表示serverid为web2,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用, 
    133.        #fall 3是3次失败觉得服务器不可用,weight代表权重 
    134.  
    135. ###################################backend server_blog############################################### 
    136. backend server_blog 
    137.        mode http            #http的7层模式 
    138.        balance roundrobin   #负载均衡的方式,roundrobin平均方式 
    139.        cookie SERVERID      #同意插入serverid到cookie中,serverid后面能够定义 
    140.        option httpchk GET /index.html #心跳检測的文件 
    141.        server blog1 192.168.16.2:80 cookie blog1 check inter 1500 rise 3 fall 3 weight 1  
    142.        #服务器定义。cookie 1表示serverid为web1,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用。fall 3是3次失败觉得服务器不可用,weight代表权重 
    143.        server blog2 192.168.16.3:80 cookie blog2 check inter 1500 rise 3 fall 3 weight 2 
    144.         #服务器定义,cookie 1表示serverid为web2,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用。fall 3是3次失败觉得服务器不可用。weight代表权重 
    145.  
    146. ###################################backend server_bbs############################################### 
    147.  
    148. backend server_bbs 
    149.        mode http            #http的7层模式 
    150.        balance roundrobin   #负载均衡的方式,roundrobin平均方式 
    151.        cookie SERVERID      #同意插入serverid到cookie中。serverid后面能够定义 
    152.        option httpchk GET /index.html #心跳检測的文件 
    153.        server bbs1 192.168.16.2:80 cookie bbs1 check inter 1500 rise 3 fall 3 weight 1  
    154.        #服务器定义。cookie 1表示serverid为web1,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用。fall 3是3次失败觉得服务器不可用,weight代表权重 
    155.        server bbs2 192.168.16.3:80 cookie bbs2 check inter 1500 rise 3 fall 3 weight 2 
    156.         #服务器定义,cookie 1表示serverid为web2,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用,fall 3是3次失败觉得服务器不可用,weight代表权重 


    样例
    mysql

    1. 加入监控MySQL状态的port
    # vi /etc/services

    mysqlcheck      6033/tcp                        # MySQL status check

    2. 使用xinetd守护进程执行MySQL状态检測
    # cat /etc/xinetd.d/mysqlchk

    service mysqlcheck
    {
            disable         = no
            flags           = REUSE
            socket_type     = stream
            port            = 6033
            wait            = no
            user            = root
            server          = /usr/local/haproxy/sbin/mysqlchk_status.sh
            log_on_failure  += USERID
    }

    3. 状态检測脚本
    # vi /usr/local/haproxy/sbin/mysqlchk_status.sh

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    #/bin/bash 
    MYSQL_HOST="localhost"
    MYSQL_PORT="3306"
    MYSQL_USERNAME="root"
    MYSQL_PASSWORD="123456"
     
    ERROR_MSG=/usr/bin/mysql --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USERNAME --password=$MYSQL_PASSWORD -e "show databases;"
     
    if [ "$ERROR_MSG" != "" ]
    then
            # mysql is fine, return http 200
            /bin/echo -e "HTTP/1.1 200 OK
    
    "
            /bin/echo -e "Content-Type: Content-Type: text/plain
    
    "
            /bin/echo -e "
    
    "
            /bin/echo -e "MySQL is running.
    
    "
            /bin/echo -e "
    
    "
    else
            # mysql is fine, return http 503
            /bin/echo -e "HTTP/1.1 503 Service Unavailable
    
    "
            /bin/echo -e "Content-Type: Content-Type: text/plain
    
    "
            /bin/echo -e "
    
    "
            /bin/echo -e "MySQL is *down*.
    
    "
            /bin/echo -e "
    
    "
    fi

    # chown haproxy.haproxy /usr/local/haproxy/sbin/mysqlchk_status.sh

    4. HAproxy日志
    # touch /var/log/haproxy.log
    # chown haproxy.haproxy /var/log/haproxy.log
    编辑/etc/syslog.conf文件,加入例如以下语句

    local0.*                                                /var/log/haproxy.log

    5. HAProxy配置文件
    [root@localhost htdocs]# cat /usr/local/haproxy/conf/haproxy.conf

    global
            maxconn 4096
            daemon
            pidfile /usr/local/haproxy/run/haproxy.pid
            #debug
            #quiet
            user haproxy
            group haproxy
     
    defaults
            log     global
            mode    http
            option  httplog
            option  dontlognull
            log 127.0.0.1 local0
            retries 3
            option redispatch
            maxconn 2000
            contimeout      5000
            clitimeout      50000
            srvtimeout      50000
     
    listen  admin_stats 192.168.0.1:80
            mode        http
            stats uri   /dbs
            stats realm     Global statistics
            stats auth  test:123456
     
    listen  proxy-mysql 0.0.0.0:23306
            mode tcp
            balance roundrobin
            option httpchk OPTIONS * HTTP/1.1
    Host: www
            server db01 192.168.0.1:3306 weight 1 check port 6033 inter 1s rise 2 fall 2
            server db02 192.168.0.2:3306 weight 1 check port 6033 inter 1s rise 2 fall 2
            option tcpka

    6. HAProxy启动脚本
    # cat /etc/init.d/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
    46
    47
    48
    49
    50
    51
    52
    53
    54
    
    #! /bin/sh
    set -e
     
    PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/haproxy/sbin
    PROGDIR=/usr/local/haproxy
    PROGNAME=haproxy
    DAEMON=$PROGDIR/sbin/$PROGNAME
    CONFIG=$PROGDIR/conf/$PROGNAME.conf
    PIDFILE=$PROGDIR/run/$PROGNAME.pid
    DESC="HAProxy daemon"
    SCRIPTNAME=/etc/init.d/$PROGNAME
     
    # Gracefully exit if the package has been removed.
    test -x $DAEMON || exit 0
     
    start()
    {
            echo -n "Starting $DESC: $PROGNAME"
            $DAEMON -f $CONFIG
            echo "."
    }
     
    stop()
    {
            echo -n "Stopping $DESC: $PROGNAME"
            haproxy_pid=cat $PIDFILE
            kill $haproxy_pid
            echo "."
    }
     
    restart()
    {
            echo -n "Restarting $DESC: $PROGNAME"
            $DAEMON -f $CONFIG -p $PIDFILE -sf $(cat $PIDFILE)
            echo "."
    }
     
    case "$1" in
      start)
            start
            ;;
      stop)
            stop
            ;;
      restart)
            restart
            ;;
      *)
            echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
            exit 1
            ;;
    esac
     
    exit 0

  • 相关阅读:
    APP开发的模式
    微信小程序的传值方式
    面试题总结
    github上传文件的步骤
    python使用笔记15--操作Excel
    python使用笔记14--商品管理小练习
    python使用笔记13--清理日志小练习
    python使用笔记12--操作mysql数据库
    python使用笔记11--时间模块
    python使用笔记10--os,sy模块
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/7363472.html
Copyright © 2020-2023  润新知