haproxy reverse proxy configuration function

scenes to be used

If you want to achieve such an environment: haproxy 4 nginx reverse proxy nodes, nginx1 and nginx2 combine php dynamic web services, nginx3 and nginx4 provide static web services. As shown below:

haproxy reverse proxy configuration function

Since the default configuration file and timeout settings related to relatively unreasonable, it is proposed to amend these times. Some also recommended that you turn on or off the items also try to open or close.

haproxy configuration instructions

Haproxy on installation and configuration, you can see HaProxy mounted and common commands

haproxy default configuration instructions

#查看默认 haproxy.cfg 配置文件
cat /usr/local/haproxy/conf/haproxy.cfg

global
    log         127.0.0.1 local2      # 需要设置/etc/rsyslog.conf加上local2设备的日志记录级别和日志路径
    chroot      /usr/local/haproxy    #这里通过编译安装到/usr/local/haproxy,yum安装默认在/var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000                  # 这是前端对外的最大连接数。代理http时,1G空闲内存承载20000以上没大问题
    user        haproxy
    group       haproxy
    daemon
    stats socket /var/lib/haproxy/stats  # 开启动态查看、管理haproxy的状态文件
                                         # 另外建议设置spread-checks全局项,且百分比建议为2-5之间
defaults
    mode                    http         # 7层http代理,另有4层tcp代理
    log                     global
    option                  httplog      # 在日志中记录http请求、session信息等
    option                  dontlognull  # 不要在日志中记录空连接
    option http-server-close             # 后端为动态应用程序建议使用http-server-close,后端为静态建议使用http-keep-alive
    option forwardfor       except 127.0.0.0/8  # haproxy将在发往后端的请求中加上"X-Forwarded-For"首部字段
    option                  redispatch   # 当某后端down掉使得haproxy无法转发携带cookie的请求到该后端时,将其转发到别的后端上
    timeout http-request    10s     # 此为等待客户端发送完整请求的最大时长,应该设置较短些防止洪水***,如设置为2-3秒
                                    # haproxy总是要求一次请求或响应全部发送完成后才会处理、转发,
    timeout queue           1m      # 请求在队列中的最大时长,1分钟太长了。设置为10秒都有点长,10秒请求不到资源客户端会失去耐心
    timeout connect         10s     # haproxy和服务端建立连接的最大时长,设置为1秒就足够了。局域网内建立连接一般都是瞬间的
    timeout client          1m      # 和客户端保持空闲连接的超时时长,在高并发下可稍微短一点,可设置为10秒以尽快释放连接
    timeout server          1m      # 和服务端保持空闲连接的超时时长,局域网内建立连接很快,所以尽量设置短一些,特别是并发时,如设置为1-3秒
    timeout http-keep-alive 10s     # 和客户端保持长连接的最大时长。优先级高于timeout http-request高于timeout client
    timeout check           10s     # 和后端服务器成功建立连接后到最终完成检查的时长(不包括建立连接的时间,只是读取到检查结果的时长),
                                    # 可设置短一点,如1-2秒
    maxconn                 3000    # 默认和前段的最大连接数,但不能超过global中的maxconn硬限制数

Description ⚠️:

(1) haproxy is a single process, event-driven software model, work efficiency has been very good at single-process, multi-process open / multi-instance is not recommended.

(2) maxconninstructions to control the maximum number of concurrent connections may be provided at a plurality of different setting positions, different means:

  <1> 设置在global段或frontend/listen/defaults段的maxconn代表的是和客户端(即frontend)的最大连接并发数;其中global段的值是硬限制,frontend/listen/defaults段的maxconn值不能超过global段的值。

  <2> 设置在server指令中时,代表的是haproxy和某台后端服务器维持的最大并发连接数。

  <3> 前端的最大并发数(即global段的maxconn)可以根据内存来估算,haproxy为每个连接维持两个缓存区,每个大致16K左右,加上一些额外数据,共约33-34K左右,因此理论上1G的空闲内存能维持2W-2.5W个纯HTTP的并发连接(只是理论上),如果代理的是https,则允许的最大并发数量要小的多。前端maxconn默认值为2000,非常有必要将其增加几倍。一般代理纯http服务时,如果后端能处理及时,这里设置20000以上都不会有什么问题。以上只是大致估算代理能力,实际设置时必须根据后端处理能力以及haproxy自身能力设置前端maxconn,否则将前端接进来后端也无法立即处理。

  <4> 后端所有服务器的maxconn值之和应接近前端的maxconn值,计算两者差距时,还需要考虑后端的等待队列长度maxqueue。其中和静态web服务器的maxconn可以设置大一些。

After modifying the configuration described demand haproxy

global
    log         127.0.0.1 local2
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     20000
    user        haproxy
    group       haproxy
    daemon
    stats socket /var/lib/haproxy/stats
    spread-checks 2
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    timeout http-request    2s
    timeout queue           3s
    timeout connect         1s
    timeout client          10s
    timeout server          2s
    timeout http-keep-alive 10s
    timeout check           2s
    maxconn                 18000 

frontend http-in
    bind             0.0.0.0:80                 # 表示haproxy监听所有地址,监听的端口为80
    mode             http
    log              global
    capture request  header Host len 20
    capture request  header Referer len 60
    ####### 定义访问控制,表示url以.css .js .html .php结尾的分别调度到哪台服务器上访问 #########
    #ACL本意是access control list(访问控制列表),用来定义一组黑名单或白名单。
    acl url_static   path_beg  -i /static /images /stylesheets     
    acl url_static   path_end  -i .jpg .jpeg .gif .png .ico .bmp .css .js
    acl url_static   path_end  -i .html .htm .shtml .shtm .pdf .mp3 .mp4 .rm .rmvb .txt
    acl url_static   path_end  -i .zip .rar .gz .tgz .bz2 .tgz
    ####### usr_backend表示使用backend服务,if表示如果满足url_static这个条件就调度到这台服务器上 ########
    use_backend      static_group   if url_static
    #不满足则响应backend的默认动态页面
    default_backend  dynamic_group

backend static_group
    balance            roundrobin        #haproxy反向代理调度算法。如果后端是静态web,建议使用roundrobin算法。
    option             http-keep-alive   #分析并处理所有的request和response(默认),当后端为静态web或静态缓存服务器时,使用http-keep-alive模型。由于响应速度快,频繁建立tcp连接的代价比较大;
    http-reuse         safe              #开启 haproxy 连接重用功能,safe:这是建议使用的策略。
    option httpchk     GET /index.html   #开启 haproxy 健康检查,本例是基于http协议检查。默认会使用tcp协议进行检查,如果要基于其它协议检查,需要使用协议对应的option指令显式指定要检查的对象。且前提是server中必须指定check,这是控制检查与否的开关。
    http-check expect  status 200        #使用http-check expect指定要检查到状态码200才认为健康。如果不指定http-check expect指令,那么基于http协议检查的时候,只要状态码为2xx或3xx都认为是健康的。
    server staticsrv1  192.168.100.62:80 check rise 1 maxconn 5000  #check设置的是是否开启健康检查功能,以及检查的时间间隔、判断多少次不健康后就认为后端下线了以及成功多少次后认为后端重新上线了。
    server staticsrv2  192.168.100.63:80 check rise 1 maxconn 5000  #rise <count>:设定健康状态检查中,某离线的server从离线状态转换至正常状态需要成功检查的次数;
                                                                    #maxconn <maxconn>:指定此服务器接受的最大并发连接数;如果发往此服务器的连接数目高于此处指定的值,其将被放置于请求队列,以等待其它连接被释放;
backend dynamic_group
    cookie appsrv insert nocache      #向响应报文中插入了一个cookie,保证被调度过的服务端和客户端能保持会话。
    balance roundrobin                #如果后端需要保持会话信息,但又不使用cookie时,可以使用源地址hash算法source,保证将同一客户端引导到同一后端服务器上。如果使用cookie,则可以使用roundrobin或leastconn算法。源地址hash算法,一般只在没有办法的时候但又要调度到同一后端服务器时,才作为最后手段。
    option http-server-close          #处理完第一个response后关闭和server端的连接,但和客户端的连接仍然保持,后端为动态应用程序服务器组建议使用此模式。
    option httpchk     GET /index.php #设置通过获取index.php来做健康状况检查
    http-check expect  status 200     #使用http-check expect指定要检查到状态码200才认为健康。
    server appsrv1 192.168.100.60:80  check rise 1 maxconn 3000 cookie appsrv1  #cookie <value>:为指定server设定cookie值,此处指定的值将在请求入站时被检查,第一次为此值挑选的server将在后续的请求中被选中,其目的在于实现持久连接的功能;
    server appsrv2 192.168.100.61:80  check rise 1 maxconn 3000 cookie appsrv2

listen report_stats
        bind 0.0.0.0:8081                        #监听端口
        stats refresh 30s                  #统计页面自动刷新时间 
        stats enable                       #启用管理界面
        stats hide-version                 #隐藏统计页面上HAProxy的版本信息
        stats uri    /hastats              #统计页面url 
        stats realm  "pls enter your name" #统计页面密码框上提示文本 
        stats auth   admin:admin           #统计页面用户名和密码设置 
        stats admin  if TRUE               #如果登录成功就可以管理在线服务器

##### 定义错误页面 #####
errorfile 403 /etc/haproxy/errorfiles/403.http
errorfile 500 /etc/haproxy/errorfiles/500.http
errorfile 502 /etc/haproxy/errorfiles/502.http
errorfile 503 /etc/haproxy/errorfiles/503.http

The above configuration:

  • (1) static requests and assigned to static_group roundrobin scheduled to do at the same time by acquiring index.html health check, in addition to the functions provided and a rear end connected haproxy reuse.

  • (2) dynamically assigned to requests and dynamic_group roundrobin scheduling, but insert a cookie in response to the message, is scheduled guaranteed service over and client can keep the session. It also set up to do the health checks by obtaining index.php.

Configuring nginx and php + php-fpm

yum -y install nginx php php-fpm

To distinguish, respectively index.php nginx1 / nginx2 of, index.html file nginx3 / nginx4 added source host in response to prompts, and set the cookie file items in php. Wherein the content of index.php reference to the following:

<h1>response from webapp 192.168.100.60</h1>
<?php
    session_start();
    echo "Server IP: "."<font color=red>".$_SERVER['SERVER_ADDR']."</font>"."<br>";
    echo "Server Name: "."<font color=red>".$_SERVER['SERVER_NAME']."</font>"."<br>";
    echo "SESSIONNAME: "."<font color=red>".session_name()."</font>"."<br>";
    echo "SESSIONID: "."<font color=red>".session_id()."</font>"."<br>";
?>

test. Php page returns the contents of which roughly like this:

haproxy reverse proxy configuration function

Reference Documents

Guess you like

Origin blog.51cto.com/wutengfei/2467834