Haproxy for reverse proxy and load balancing

Source: Internet
Author: User
Tags 303 status code haproxy

Reverse proxy Server features: Web caching (acceleration), reverse proxy, content routing (forwarding requests to a specific server based on traffic and content type, etc.), transcoding

Cache: Reduce redundant content transmission, save bandwidth, alleviate network bottleneck, reduce the request pressure on the original server, reduce the transmission delay, public cache everyone can use, private cache with sensitive data only for the qualification of a class or a person to use

Nginx can implement the cache function, Haproxy can not implement the cache function, here only to explain its reverse proxy function and load balancing function

Yum install haproxy Master profile haproxy.cfg turn on log function: Edit/etc/rsyslog.conf file $modload imudp$udpserverrun  514   #开启udp514端口local2 .*                                                   /var/log/haproxy.log Edit/etc/haproxy/haproxy.cfg File:log          127.0.0.1 local2 Configuring a load-balanced backend host:global    log          127.0.0.1 local2    chroot      /var/ lib/haproxy    pidfile     /var/run/haproxy.pid     maxconn     4000   defines the total maximum number of connections to the client (facing the client side)      User    &nbsP;   haproxy    group       haproxy     daemon    # turn on stats unix socket     stats socket /var/lib/haproxy/stats#---------------------------------------- -----------------------------# main frontend which proxys to the backends#- --------------------------------------------------------------------frontend  main *:80    #第一种方式 #        bind *:80     #第二种方式 #         bind *:8080     #只能用于frontend,  listen; #        maxconn   can also be defined here or after listen, Defines the maximum number of concurrent connections for a single instance if the global segment definition is the total of all instances    default_backend              websrvs#---------------------------------------------------------------------# round robin  balancing between the various backends#--------------------------------------------------- ------------------Backend websrvs    balance     roundrobin     server  web1 192.168.20.7:80 check  #定义的名字web1会被加到请求首部发到后端, Useful when a backend has a virtual host     server  web2 192.168.20.8:80 check

Several scheduling algorithms:

Balance: Indicates the scheduling algorithm;
Dynamic: Weights can be dynamically adjusted
Static: Adjustment weights do not take effect in real time
Roundrobin: Polling, dynamic algorithm, each back-end host supports up to 4,128 connections;
STATIC-RR: Polling, static algorithm, no limit on the number of support per backend host;
Leastconn: Scheduling based on the number of loads on the backend host, only for long-connected sessions; dynamic;
Hash-type:
Map-based: Modulus method, static;
Consistent: consistent hashing; dynamic;

The following four scheduling algorithms are based on two of the above Hash-type

Source
URI: Hashes the left half of the URI (the part before the tag) or the entire URI, but binds to the backend server after the total weight of the backend server
Url_param: Dispatched according to the value of the specified parameter in the URL, calculates the value as a hash and divides it by the total weight;
HDR (<name>): dispatched according to the header specified in the request packet (e.g. use_agent, referer, hostname); The value of the specified header is hashed to calculate the value divided by the total weight;
Example:

Backend Websrvs balance HDR (user-agent) hash-type consistent server Web1 192.168.20.7:80 Check server we B2 192.168.20.8:80 Check

Test:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/75/68/wKioL1Y4epeRl-WVAACLgXcUsIs267.jpg "title=" 1.png " alt= "Wkiol1y4eperl-wvaaclgxcusis267.jpg"/>

Mode: What protocol is based on health condition detection
Haproxy mode of operation; the default is TCP; There are three types: TCP, HTTP, health

Only the client and frontend, the backend is HTTP communication to use HTTP mode

Log can also be specified in the front segment:

Frontend main *:80 Log global log 127.0.0.2 Local3

Defining the latter segment with Use_backend and ACLs

Use_backend Dynamic If Url_dyn
Use_backend static if Url_css url_img extension_img

Parameters that can be added after the server segment:

backup: Set as a standby server, only other servers in the load balancing scenario are not available to enable this server Check: Initiates a health check on this server, which can be used to perform finer settings with additional parameters such as: &NBSP;&NBSP;INTER&NBSP;<DELAY>: Sets the time interval for health checks, in milliseconds, The default is 2000, or you can use Fastinter and downinter to optimize this time delay based on server-side state,   rise <count>: Setting health Checks, The number of times an offline server transitions from offline to a normal state requires a successful check;   fall <count>: Check the number of times the server needs to be checked to transition from a normal state to an unavailable state;cookie  <value>: Sets the cookie value for the specified server, the value specified here will be checked when the inbound is requested, and the first server picked for this value will be selected in subsequent requests for the purpose of implementing the functionality of the persistent connection;maxconn < Maxconn>: Specifies the maximum number of concurrent connections accepted by this server, and if the number of connections destined to this server is higher than the value specified here, it will be placed in the request queue waiting for other connections to be released;maxqueue <maxqueue> : Sets the maximum length of the request queue; Observe <mode>: Determines its health status by observing the server's communication status, default is disabled, its supported types are "Layer4" and "Layer7", "Layer7" Can only be used for HTTP proxy scenarios; REDIR&NBSP;<PREFIX>: Enable redirection, both get and head requests destined for this server are responded with a 302 status code, and it is important to note that you cannot use a relative address after prefix. avoid causing loops; For example:   server srv1 172.16.100.6:80 redir http://imageserver.magedu.com  checkweight <weight>: Weight, default is 1, maximum value is 256,0 means no load balancing; 

Define health Check methods you can use option:

Option httpchkoption httpchk <uri>option httpchk <method> <uri> Example: Backend https_relay mode tcp O   Ption httpchk OPTIONS * http/1.1\r\nhost:\ www.lee123.com server apache1 192.168.1.1:443 Check Port 80 use case: server first 172.16.100.7:1080 Cookie First check inter 1000server second 172.16.100.8:1080 cookie second check Inter 1000

To implement session sticky based on browser cookies:

Key points: (1) Each server has its own unique cookie identifier, (2) defined in backend to manipulate its cookiebackend websrvs balance Roundrobin cookie SERVER When user request scheduling is complete ID Insert NoCache Indirect server web1 192.168.20.7:80 Check cookie websrv1 server web2 192.168.20.8:80 check Cook IE Websrv2

Test: Notice the WEBSRV1 keyword on the cookie's head?

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/75/6B/wKioL1Y4qbmzOZf2AAIwdL1Eqd0065.jpg "title=" 2.png " alt= "Wkiol1y4qbmzozf2aaiwdl1eqd0065.jpg"/>

To open the statistics page:

Listen statistics bind *:9090 stats enable stats hide-version #stats scope. Stats uri/haproxyadmin?stats Stats Realm "haporxy\ Statistics" stats auth admin:mageedu stats admin If TRUE

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/75/6E/wKiom1Y4rQLD9KOkAAViXWw2_QI398.jpg "title=" 3.png " alt= "Wkiom1y4rqld9kokaavixww2_qi398.jpg"/>

Record additional information in the log:
Capture Request Header
Capture response Header

When mode is HTTP, a rich log message is logged:
Option Httplog----turned on by default

Error page Redirection:
ErrorFile: Use haproxy host local file for response;
Errorloc, errorloc302: Responds with the specified URL, the response status code is 302, and does not apply to other request methods other than get;
errorloc303: Returns 303 status code;

To add a request or response message header:
Reqadd
Rspadd

Frontend main bind *:80 bind *:8080 rspadd via:\ node1.lee.com default_backend Websrvs

A VIA is present:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/75/6E/wKiom1Y4vFPgmX6qAAIDhluDxZE046.jpg "title=" 4. PNG "alt=" wkiom1y4vfpgmx6qaaidhludxze046.jpg "/>

Example of static and dynamic separation: frontend  main    bind *:80    bind *:8080     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             appsrvs#--------- ------------------------------------------------------------# static backend for serving  up images, stylesheets and such#---------------------------------------------------- -----------------    backend static       balance roundrobin        server static1 192.168.20.7 check        server static2 192.168.20.8 check    backend appsrvs        balance     roundrobin        option forwardfor except 127.0.0.1 header X-Client        option httpchk       cookie  serverid insert indirect nocache       server   Web1 192.168.20.7:80 check cookie web1       server   web2 192.168.20.8:80 check cookie web2


This article is from the "After Tomorrow" blog, please be sure to keep this source http://leeyan.blog.51cto.com/8379003/1709396

Haproxy for reverse proxy and load balancing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.