Haproxy provides high availability, load balancing, and proxies based on TCP and HTTP applications, supporting virtual hosting, which is a free, fast, and reliable solution. Haproxy is especially useful for Web sites that are heavily loaded, and often require session-hold or seven-tier processing. The haproxy runs on the current hardware and can support tens of thousands of concurrent connections. and its operating mode makes it easy and safe to integrate into your current architecture, while protecting your Web server from being exposed to the web.
1. Installation
[[email protected] varnish]# yum install haproxy
2. Adjusting parameters
Nbproc <number>: Number of processes to start haproxy; Official recommendation a default one
Maxconn the maximum number of connections per process one connection 33KB 1g memory can create 20000-25000 processes, this depends on the specific adjustment
Maxconnrate Maximum Create connection rate
Maxse***ate Maximum number of creation sessions
Maxsslconn Maximum Create SSL connection default or Maxconn, prevent memory overflow, etc.
Ulimit-n <number>: The maximum number of files that can be opened per Haproxy process, the client service side, so the maximum number of connections is automatically adjusted
Timeout Client <timeout> Terminal inactivity Timeout length
Timeout Server <timeout> server-side inactivity duration
Timeout http-keep-alive long duration of persistent connection;
Timeout http-request wait for HTTP request Wensau time
Timeout Connect and server timeout time
Timeout Client-fin client disconnects default 30s
Timeout Server-fin server disconnected
Adjust the maxconn, others see the situation adjustment
3. Configure the front-end background
#调度方法
#roundrobin Dynamic algorithm: Support the weight of the runtime adjustment, support slow start, up to 4,095 servers per backend;
#static-RR: Static algorithm: not support the weight of the run-time adjustment and slow start, the number of back-end host No limit;
#leastconn: Recommended for use in scenes with longer sessions, such as MySQL, LDAP, etc.;
#first: According to the location of the server in the list, the top-down scheduling, the number of connections in front of the server reached the upper limit, the new request will be assigned to the next service;
#source: Source address hash;
#<scheme>://<user>:<password>@#左半部分:/<path>;<params>
#整个uri:/<path>;<params>?<query>#<frag>
#uri: Hash The left half of the URI and distribute it to a selected server after dividing the total weight of the server;
#url_param the value of the parameters in the URI listening <params> section of the user request is hashed and distributed to a selected server after dividing by the total server weight, usually used to track the user to ensure that requests from the same user are always sent to the same backend Server;
#hdr (<name>): For each HTTP request, the HTTP header specified here by <name> will be fetched for hash calculation and distributed to a selected server after dividing by the total server weight, and no valid value will be polled for scheduling; Cookies)
#调度算法
#hash-type
#map-based: The hash data structure is a static array in addition to the weighted redundancy method;
#consistent: Consistent hash, hash data structure is a tree;
#mode {tcp|http|health}
#tcp: Implements the agent based on Layer4, can proxy MySQL, pgsql, SSH, SSL and other protocols;
#http: Used only when the agent's protocol is HTTP;
# Health: A response mode that works as a healthy state check that disconnects when the connection request arrives and responds with "OK";
#server parameters
#server <name> <address>[:p ort] [settings ...]
#<name>: The internal name of the server on Haproxy; the log and warning message;
#<address>: Server address, support for using hostname;
#[:[port]]: port mapping; omitting Represents the port bound in bind,
#[param*]: parameter
#maxconn <maxconn>: The maximum number of concurrent connections for the current server;
#backup: Sets the current server as the standby server;
# Check: Health status detection for current server,
#addr: IP address used for detection,
#port: Detection for this port,
#inter <delay>: time interval between two consecutive detections, The default is 2000ms;
#rise <count>: The number of consecutive test results for "success" to mark the server as available; default is 2;
#all <count>: The number of consecutive detections that failed to mark the server as unavailable; default is 3;
# Note: httpchk, "Smtpchk", "Mysql-check", "Pgsql-check" and "Ssl-hello-chk" are used to define the application layer detection method;
#cookie <value> : Specifies its cookie value for the current server to implement cookie-based session stickiness; a fixed value, the second time to find the corresponding host
#disabled: marked unavailable;
#redir <prefix> : Redirect requests for all get and head classes destined for this server to the specified url;https://www.baidu.com
#weight <weight>: weight, default = 1;
frontend main *:80 mode tcp default_backend appbackend app balance source hash-type map-based server node2 192.168.1.201:80 check inter 1000 rise 1 fall 2 weight maxconn 2000 server node3 192.168.1.202:80 check
4. Configuration Status page and authentication (base64)
可以写在backend 和 frontend中listen stats:10080 # 也可以配置backend 或者 frontend 或者 listen stats enable stats uri /haadmin?admin stats realm "HAProxy Statistics" stats auth admin:admin stats auth admin1:admin1 stats admin if TRUE #状态页面设置 慎用
5. TCP Proxy
listen sshsrvs :10022 mode tcp maxconn 10 balance leastconn server ssh1 192.168.1.201:22 check server ssh2 192.168.1.202:22 check
6. cookie-based binding
backend websrvs cookie WEBSRV insert nocache indirect server srv1 172.16.100.6:80 weight 2 check rise 1 fall 2 maxconn 3000 cookie srv1 server srv2 172.16.100.7:80 weight 1 check rise 1 fall 2 maxconn 3000 cookie srv2
#第一次来添加cookie值, the second time, based on the cookie value to the specified back-end host
7, Proxy IP default will have
默认开启的option forwardfor [ except <network> ] [ header <name> ] [ if-none ]option forwardfor header X-Client 重命名
8. Custom error page
<code>:is the HTTP status code. Currently, HAProxy is capable of generating codes 200, 400, 403, 408, 500, 502, 503, and 504.errorfile 400 /etc/haproxy/errorfiles/400badreq.httperrorfile 408 /dev/null # workaround Chrome pre-connect bugerrorfile 403 /etc/haproxy/errorfiles/403forbid.httperrorfile 503 /etc/haproxy/errorfiles/503sorry.http errorloc <code> <url>errorloc 403 http://www.baidu.comerrorloc302 <code> <url>#_____________________________________________________________ acl invalid_src src 192.168.1.104 block if invalid_src errorfile 403 /root/error.html
9. Header
reqadd <string> [{if | unless} <cond>] rspadd <string> [{if | unless} <cond>]reqdel <search> [{if | unless} <cond>]reqidel <search> [{if | unless} <cond>] (ignore case)rspdel <search> [{if | unless} <cond>]rspidel <search> [{if | unless} <cond>] (ignore case)#_________________________________________________________________________frontend main *:80 rspadd X-var:\ Haproxy rspdel X-Powered-By default_backend app
10. Log
LOG: Define a global syslog server, up to two can be defined, log 127.0.0.1 local2log-format <string>: Log server destined to the local computer by default; (1) local2.*/var/ Log/local2.log (2) $ModLoad imudp $UDPServerRun 514[[email protected] varnish]# tail/var/log/haproxy.logj Un 7 14:56:57 localhost haproxy[8676]: 192.168.1.104:64969 [07/jun/2018:14:56:57.477] main App/node2 0/0/0/2/2 200 1734- ---vn 2/2/0/0/0 0/0 "get/index.php http/1.1" >>> Feb 6 12:14:14 localhost haproxy[14389]: 10.0.1.2:33317 [06/feb/2009:12:14:14.655] http-in static/srv1 10/0/30/69/109 2750------1/1/1/1/0 0/0 {1wt.eu} {} "GE t/index.html http/1.1 "Field Format Extract from the example above 1 Process_nam E ' [' pid ']: ' haproxy[14389]: 2 client_ip ': ' Client_port 1 0.0.1.2:33317 3 ' [' accept_date '] ' [06/feb/2009:12:14:14.655] 4 frontend_name Http-in 5 backend_name '/' server_name STATIC/SRV1 6 Tq '/' Tw ' /' Tc '/' Tr '/' tt* 10/0/30/69/109 7 Status_code 8 bytes_read* 2750 9 Captured_request_cook Ie-10 Captured_response_cookie -One termination_state----actconn '/' feconn '/' Beconn ' /' srv_conn '/' retries* 1/1/1/1/0 srv_queue '/' Backend_queue 0/0 14 ' {' captured_request_headers* '} ' {haproxy.1wt.eu} ' {' captured_response_headers* '} ' {} "" ' Http_request ' "'" get/index.html http/1.1 "Tq waits for the client to send a report Text time TW queue wait time lengthTC Create connection long Tr waits for server to send response to Agent time TT receive message length Actconn log record time current process connection number Feconn logging time front end connection number Beconn log record when back end connected Number of Srv_conn log records when the current number of active connections retries the number of times the log is reconnected #捕获并记录日志 capture request header Host Len capture R Equest header user-agent Len Capture request header X-forwarded-for Len Capture request header Referer Len 2 Capture response header Server Len response capture header Server-id Len 40log-format%t\%t\ some\ textlog-fo Rmat%{+q}o\%t\%s\%{-q}r
11. Compression
compression algo <algorithm> ...:启用http协议的压缩机制,指明压缩算法gzip, deflate;compression type <mime type> ...:指明压缩的MIMI类型#___________________________________________________________compression type application/javascript text/plaincompression algo gzip
12, Static and dynamic separation
frontend main *:80 acl invalid_src src 192.168.1.104 block if invalid_src #如果源地址是192.168.1.104 invalid_src=True ;如果invalid_src是真就blockfrontend 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 #else default_backend app
13, virtual host static and dynamic separation configuration
frontend main *:80 acl www_proxy hdr_dom(host) -i www.proxy.develop acl url_static path_end -i .jpg .gif .png .css .js use_backend www_proxy_static if url_static use_backend www_proxy_dynamic if www_proxy ! url_staticbackend www_proxy_static server node1 192.168.1.201:80 checkbackend www_proxy_dynamic server node2 192.168.1.202:80 check
14, HTTPS (HTTP->HTTPS)
frontend https_frontend bind *:443 ssl crt /etc/haproxy/demo.pem default_backend appfrontend main *:80 acl ssl_proxy hdr_dom(host) -i www.proxy2.develop redirect scheme https if ssl_proxy
Linux Haproxy Agent Introduction