Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to fully install and use the agent software HAProxy on CentOS

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to completely install and use the agent software HAProxy on CentOS". The explanation in the article is simple and clear, and easy to learn and understand. please follow the editor's train of thought to study and learn "how to completely install and use the agent software HAProxy on CentOS".

A brief introduction to HAProxy

(1) HAProxy is an agent software that provides high availability, load balancing and based on TCP (layer 4) and HTTP (layer 7) applications, and supports virtual hosts. It is a free, fast and reliable solution. HAProxy is especially suitable for heavily loaded web sites, which usually require session persistence or seven-tier processing. HAProxy runs on today's hardware and can support tens of thousands of concurrent connections. And its mode of operation makes it easy and secure to integrate into your current architecture, while protecting your web server from being exposed to the network.

(2) HAProxy implements an event-driven, single-process model that supports a very large number of concurrent connections. Multiprocess or multithreaded models rarely handle thousands of concurrent connections due to memory constraints, system scheduler limitations, and ubiquitous locks. The event-driven model does not have these problems because it implements all these tasks on the client side (User-Space) with better resource and time management. The drawback of this model is that on multi-core systems, these programs are usually poorly scalable. This is why they have to optimize so that each CPU time slice (Cycle) does more work.

(3) HAProxy supports connection rejection: because the overhead of maintaining an open connection is very low, sometimes we need to limit the attack worms (attack bots), that is, to limit their connection opening in order to limit their harm. This has been developed for a website caught up in a small DDoS attack and has been saved

There are many sites, which is an advantage that other load balancers do not have.

(4) HAProxy supports fully transparent proxy (typical features of hardware firewall): you can use client IP address or any other address to connect to the back-end server. This feature can only be used with the cttproxy patch in the Linux 2.4 Universe 2.6 kernel. This feature also makes it possible to handle part of the traffic for a particular server without changing the server's address.

Performance

HAProxy maximizes performance with the help of several common technologies on OS.

1. Single-process and event-driven model significantly reduces the overhead and memory footprint of context switching.

2 the event checker event checker allows it to detect any event of any connection in real time in highly concurrent connections.

3. Where available, the single buffer (single buffering) mechanism can read and write without copying any data, which saves a lot of CPU clock cycles and memory bandwidth.

4. With the help of splice () system call on Linux 2.6 (> = 2.6.27.19), HAProxy can achieve zero replication forwarding (Zero-copy forwarding) and zero replication initiation (zero-starting) in OS of Linux 3.5 and above.

5. The memory allocator can achieve instant memory allocation in a fixed memory pool, which can significantly reduce the time it takes to create a session.

6. Tree storage: focusing on using the elastic binary tree developed by the author many years ago, it realizes the low overhead of O (log (N)) to maintain timer commands, keep running queue commands and manage polling and minimum connection queues.

7, optimized HTTP header analysis: the optimized header analysis function avoids rereading any memory areas during HTTP header analysis

8, elaborate reduction of expensive system calls, most of the work is done in user space, such as time reading, buffer aggregation, and enabling and disabling of file descriptors.

All of these subtle optimizations achieve a fairly low CPU load above a medium load, and even in very high load scenarios, 5% user space occupancy and 95% system space occupancy are very common, which means that the HAProxy process consumption is more than 20 times lower than the system space consumption. Therefore, it is very important to tune the performance of OS. Even if the user space occupancy is doubled, the CPU occupancy rate is only 10%, which explains why layer 7 processing has a limited impact on performance. As a result, the layer 7 performance of HAProxy can easily exceed that of hardware load balancing devices on high-end systems.

In a production environment, using HAProxy on layer 7 processing as an emergency solution for expensive high-end hardware load balancing equipment failures can also be seen for a long time. Hardware load balancing devices process requests at the "message" level, which is more difficult to support cross-message requests (request across multiple packets), and they do not buffer any data, so they have a long response time. Correspondingly, the software load balancing device uses TCP buffering, which can establish very long requests and has a large response time.

At present, there are three main versions of HAProxy: 1.3,1.4,1.5 centOS 6.6 comes with a 1.5 RPM package.

Second, install and configure HAProxy

The following experimental environment is CentOS6.6 i686 platform.

1, install haproxy

The code is as follows:

[root@LB ~] # yum install-y haproxy # install directly using RPM

[root@LB ~] # rpm-qi haproxy # version 1.5.4

Name: haproxy Relocations: (not relocatable)

Version: 1.5.4 Vendor: CentOS

Release: 2.el6 Build Date: Thu 23 Jul 2015 04:26:35 PM PDT

Install Date: Sat 29 Aug 2015 06:49:30 PM PDT Build Host: c6b9.bsys.dev.centos.org

Group: System Environment/Daemons Source RPM: haproxy-1.5.4-2.el6.src.rpm

Size: 2542578 License: GPLv2+

Signature: RSA/SHA1, Fri 24 Jul 2015 01:39:18 PM PDT, Key ID 0946fca2c105b9de

Packager: CentOS BuildSystem

URL: http://www.haproxy.org/

Summary: HAProxy is a TCP/HTTP reverse proxy for high availability environments

[root@LB ~] # rpm-ql haproxy

/ etc/haproxy

/ etc/haproxy/haproxy.cfg-> configuration file

/ etc/logrotate.d/haproxy

/ etc/rc.d/init.d/haproxy

/ etc/sysconfig/haproxy

/ usr/bin/halog

/ usr/bin/iprange

/ usr/sbin/haproxy

[root@LB ~] # cd / etc/haproxy/

2, explain the configuration file in detail

The configuration file of haproxy consists of two parts: global settings and proxy settings, which is divided into five sections: global,defaults,frontend,backend,listen.

2.1 configuration file format

There are three types of configuration processing for HAProxy from the main sources of parameters:

-- the highest priority command line argument

"global" configuration section, which is used to set global configuration parameters

-- proxy related configuration segments, such as "defaults", "listen", "frontend" and "backend"

2.2 time format

Some parameters that contain values represent time, such as timeout. These values are generally in milliseconds, but other time unit suffixes can also be used.

Us: microseconds (microseconds), that is, 1,000,000 seconds

Ms: milliseconds (milliseconds), that is, 1max 1000 seconds

S: seconds (seconds)

M: minutes (minutes)

H: hours (hours)

D: days (days)

2.3 Global configuration

* process management and security-related parameters

-chroot: modify the working directory of haproxy to the specified directory and perform the chroot () operation before relinquishing permissions to improve the security level of haproxy. However, it is important to ensure that the specified directory is empty and that no user can have write permission.

-daemon: let haproxy work in the background as a daemon, which is equivalent to the "- D" option. Of course, you can also disable it with the "- db" option on the command line.

-gid: run haproxy with the specified GID. It is recommended to use a GID dedicated to running haproxy to avoid the risk caused by permission issues.

-group: same as gid, but the specified group name

-log [max level [min level]]: defines a global syslog server, with a maximum of two

-log-send-hostname []: add the current hostname to the beginning of the syslog message, either with the name specified for "string" or by default

-nbproc: specify the number of haproxy processes started. Haproxy; in daemon mode can only start one process by default. Due to various reasons such as difficulties in debugging, multi-process mode is generally used only in scenarios where a single process can only open a few file descriptors.

-pidfile:

-uid: runs the haproxy process under the specified UID identity

-ulimit-n: set the maximum number of file descriptors that can be opened by each process, which is calculated automatically by default, so it is not recommended to modify this option. The default number of files opened by the Linux single process is 1024.

-user: same as uid, but using user name

-stats: the interface for users to access statistical data

-node: defines the name of the current node, which is used when multiple haproxy processes share the same IP address in a HA scenario

-description: description of the current instance

* parameters related to performance tuning

-maxconn: sets the maximum number of concurrent connections accepted by each haproxy process, which is equivalent to the command line option "- n". The result of automatic calculation of "ulimit-n" is set with reference to this parameter.

-maxpipes: haproxy uses pipe to reassemble kernel-based tcp messages. This option is used to set the maximum number of pipe allowed per process. Each pipe opens two file descriptors, so "ulimit-n" automatically increases this value as needed; the default is maxconn/4, which usually appears to be too large.

-noepoll: disable the epoll mechanism on Linux systems

-nokqueue: disable the kqueue mechanism on BSE systems

-nopoll: disable the poll mechanism

-nosepoll: disable the heuristic epoll mechanism in Linux

-nosplice: kernel tcp reassembly is prohibited on Linux sockets, which results in more recv/send system calls; however, on Linux 2.6.25-28 series kernels, the tcp reassembly feature has bug

-spread-checks: in a scenario where there are many servers at the haproxy backend, it may cause unexpected problems to conduct a unified health check on the servers after a precise time interval. This option is used to increase or decrease the length of the check interval by a certain random length.

-tune.bufsize: set the size of buffer, the same memory condition is small, a smaller value allows haproxy to accept more concurrent connections, and a larger value allows some applications to use larger cookie information; the default is 16384, which can be modified at compile time, but the default value is strongly recommended.

-tune.chksize: sets the size of the check buffer in bytes; a larger value helps to complete text lookups based on strings or patterns on larger pages, but also consumes more system resources; modification is not recommended

-tune.maxaccept: set the number of connections that can be accepted at one time when the haproxy process kernel is scheduled to run. A larger value can bring greater throughput. By default, it is 100 in single-process mode and 8 in multi-process mode. Setting this limit to-1 is prohibited. Generally, it is not recommended to modify it.

-tune.maxpollevents: set the maximum number of events that can be handled by a system call. The default value depends on the bandwidth savings when the OS; value is less than 200, but slightly increases the network latency, while greater than 200 reduces the delay, but slightly increases the network bandwidth usage.

-tune.maxrewrite: set the buffer space reserved for the first rewrite or append. It is recommended to use a size of about 1024. When more space is needed, haproxy will automatically increase its value.

-tune.rcvbuf.client:

-tune.rcvbuf.server: sets the size of the buffer received by the server or client in the kernel socket (in bytes). Default value is highly recommended.

-tune.sndbuf.client:

-tune.sndbuf.server:

* parameters related to Debug

-debug

-quiet

* length of timeout

Timeout http request: closes a client connection when the client establishes a connection but does not request data

Timeout queue: maximum waiting time

Timeout connect: defines the timeout for haproxy to forward client requests to the back-end server

Timeout client: timeout for client inactivity

Timeout server: the timeout period for the client to wait for the server after establishing a connection with the server

Timeout http-keep-alive: defines the timeout for keeping a connection

Timeout check: timeout for health monitoring. Too short will lead to misjudgment and excessive resource consumption.

Maxconn: maximum number of connections per server

Http-server-close: when using a persistent connection, this feature enables the server to close the persistent connection in order to avoid client timeout without closing the persistent connection.

Redispatch: when using cookie-based direction, if a backend server goes down, the session will be redirected to an upstream server, which must be used.

* implement access control:

Http-request: layer 7 filtering

Tcp-request content: tcp layer filtering, four layer filtering

2.4 Agent

The agent-related configuration can be found in the following configuration section

-defaults

-frontend

-backend

-listen

The "defaults" section is used to provide default parameters for all other configuration segments, which can be reset by the next "defaults".

The "frontend" section is used to define a series of listening sockets that can accept client requests and establish connections with them.

The "backend" section is used to define a series of "back-end" servers to which the agent will forward requests from the corresponding client.

The "listen" section defines a complete proxy by associating "frontend" and "backend", which is usually only useful for TCP traffic.

All agent names can only use uppercase letters, lowercase letters, numbers,-(midline), _ (underscore),. (period) and: (colon). In addition, ACL names are case sensitive.

III. Keyword reference in configuration file

3.1 balance

The code is as follows:

Balance []

Balance url_param [check_post []]

Define load balancing algorithms that can be used for "defaults", "listen" and "backend". It is used to select a server in a load balancer scenario, which is only used when persistent information is not available or when a connection needs to be redistributed to another server. The supported algorithms are:

3.11 roundrobin: rotation based on weight, which is the most balanced and fair algorithm when the processing time of the server is evenly distributed. This algorithm is dynamic, which means that its weight can be adjusted at run time, but by design, each back-end server can only accept up to 4128 connections and supports slow start.

3.12 static-rr: rotation based on weight, similar to roundrobin, but it is a static method, so adjusting the server weight at runtime will not take effect; however, there is no limit on the number of connections to the backend server; slow startup is not supported. Under heavy load, a large number of connections will be allocated to the server when it comes back online.

3.13 leastconn (WLC): suitable for long-connected sessions, where new connection requests are sent to back-end servers with a minimum number of connections. This algorithm is recommended in scenarios with long sessions, such as LDAP, SQL, etc., but not suitable for application layer protocols with shorter sessions, such as HTTP;.

You can adjust its weight at run time

3.14 source: hash the requested source address and dispatch it to a matching server after dividing the total weight of the back-end server; this allows requests from the same client IP to always be dispatched to a specific server However, when the total number of server weights changes, such as when a server goes down or a new server is added, many client requests may be sent to a different server than the previous request; TCP-based protocol, which is commonly used in load balancing without cookie function; it defaults to static, but this feature can also be modified using hash-type

1. For the original address hash, use WLC for the first scheduling

In the source:IP layer, multiple requests located behind the same NAT server will be directed to the same upstream server, which is not conducive to load balancing. Generally, it is only used when cookie insertion is not supported and session maintenance is needed.

Cookie: application layer, with better load balancing effect

2Query hashbalance% IP: divide by weight to take the module

3.15 uri: hash the left half of the URI (the part before the "problem" tag) or the entire URI and distribute it to a matching server after dividing the total weights of the server; this allows requests for the same URI to always be sent to a specific server unless the total weight of the server changes; this algorithm is often used for proxy caching or antivirus agents to improve cache hit rates It should be noted that this algorithm only applies to HTTP back-end server scenarios; it defaults to a static algorithm, but this feature can also be modified using hash-type

3.16 url_param: the parameter specified for URL will be retrieved in each HTTP GET request; if the specified parameter is found and assigned a value by the equal sign "=", then this value will be hash performed and divided by the total weight of the server and dispatched to a matching server This algorithm can ensure that requests from the same user ID will be sent to the same specific server by tracking the user identity in the request, unless the total weight of the server changes; if the specified parameter does not appear in the request or there is no valid value, the rotation algorithm is used to schedule the request; this algorithm is static by default, but it can also use hash-type to modify this feature.

3.17 hdr (): for each HTTP request, the specified HTTP header will be retrieved; if the corresponding header does not appear or there is no valid value, the rotation algorithm is used to schedule the corresponding request It has an optional option "use_domain_only" that only calculates the domain name portion (for example, through www.feiyu.com, only the hash value of the feiyu string) when specifying that the header of a class similar to hash is retrieved to reduce the amount of computation of the hash algorithm; this algorithm is static by default, but it can also be modified using hash-type

3.18 rdp-cookie (name)

Which means that each TCP request is locked and hashed according to cookie (name).

3.2 bind

The code is as follows:

Bind []: [,...]

Bind []: [,...] Interface

This instruction can only be used for frontend and listen sections to define one or more listening sockets.

Optional, which can be hostname, IPv4 address, IPv6 address or *; when omitted and specified as * or 0.0.0.0, all IPv4 addresses of the current system will be listened to;: it can be a specific TCP port or a port range (such as 5005-5010), and the proxy server will receive client requests through the specified port It should be noted that each set of listening sockets can only be used once on the same instance, and ports less than 1024 need to be used by users with specific permissions, which may need to be defined by the uid parameter; specify the name of the physical interface, which can only be used on the Linux system; it cannot use the interface alias, but only the physical interface name, and only manage the physical interface that has the permission to specify the binding.

3.3 mode

The code is as follows:

Mode {tcp | http | health}

Set the operation mode or protocol of the instance. When implementing content exchange, the front end and back end must work in the same mode (generally speaking, HTTP mode), otherwise the instance will not be started.

Tcp: the instance runs in pure TCP mode, and a full-duplex connection will be established between the client and the server without any type of check on layer 7 messages. It is usually used in SSL, SSH, SMTP and other applications.

Http: the instance runs in HTTP mode. Client requests will be deeply analyzed before being forwarded to the back-end server, and all requests that are not compatible with RFC format will be rejected. This is the default mode.

Health: the instance works in health mode, which only responds to "OK" messages and closes the connection to inbound requests, and does not record any log information; this mode will be used to respond to health check requests from external components; currently, this mode is obsolete because the monitor keyword in tcp or http mode can perform similar functions

3.4 hash-type

The code is as follows:

Hash-type

Define the method used to map the hash code to the backend server; it cannot be used in the frontend section; the available methods are map-based and consistent, and the default map-based method is recommended in most scenarios.

The map-based:hash table is a static array of all online servers. Its hash value will be very smooth and the weight will be taken into account in the column, but it is a static method, and adjusting the weight of the online server will not take effect, which means it does not support slow startup. In addition, the server is selected based on its in the array

Location, so when a server goes down or a new server is added, most connections will be redistributed to a different server than before, for cache server work scenarios, this method is not very suitable.

Consistent: "consistent hash algorithm", the hash table is a tree structure filled by each server, which hashes the servers on the hash ring; when looking for the corresponding server in the hash tree based on the hash key, the nearest server will be selected. This method is dynamic and allows server weights to be modified at run time, so

The ability to tolerate slow start. When you add a new server, only a small number of requests are affected, so it is especially suitable for scenarios where the back-end server is cache. However, this algorithm is not very smooth, and the requests sent to each server may not achieve the ideal balance effect. Therefore, it may be necessary to adjust the weight of the server from time to time.

Weight to achieve better balance.

3.5 log

The code is as follows:

Log global

Log [[]]

Enable event and traffic logs for each instance, so they can be used for all segments. A maximum of two log parameters can be specified per instance, but if "log global" is used and two log parameters have been specified in the "global" section, the extra log parameters will be ignored.

Global: this format is used when the log system parameters of the current instance are the same as those defined in the "global" section; each instance can only define a "log global" statement once, and it does not have any additional parameters

Define the location to which the log is sent. One of the formats can be: port is the UDP protocol port, default is 514; the second format is the Unix socket file path, but you need to pay attention to the read and write permissions of chroot applications and users.

Can be one of the standard facility of syslog system

Define the log level, that is, the output information filter, which defaults to all information; when you specify a level, all log information equal to or higher than this level will be sent

3.6 maxconn

The code is as follows:

Maxconn

Sets the maximum number of concurrent connections for a front end, so it cannot be used in the backend section. For large sites, you can increase this value as much as possible to allow haproxy to manage the connection queue to avoid not being able to answer user requests. Of course, this maximum cannot exceed the definition in the "global" section. In addition, it is important to note that haproxy maintains two buffers for each connection, each buffer size of 8KB, together with other data, each connection will take up approximately the RAM space of 17KB. This means that with proper optimization, 40000-50000 concurrent connections can be maintained with available RAM space for 1GB.

If you specify an excessive value for it, in extreme scenarios, it may end up occupying more space than the available memory of the current host, which may lead to unexpected results; therefore, it is wise to set it to an acceptable value. The default is 2000.

3.7 default_backend

The code is as follows:

Default_backend

Specifies the default backend to use for the instance when there is no matching "use_backend" rule, so it cannot be applied to the backend section. When there is a content exchange between "frontend" and "backend", "use-backend" is usually used to define its matching rules; requests that are not matched by the rules are received by the backend specified by this parameter.

Specify the name of the backend used

Use case:

The code is as follows:

Use_backend dynamic if url_dyn

Use_backend static if url_css url_img extension_img

Default_backend dynamic

3.8 server

The code is as follows:

Server [: port] [param*]

Declare a server for the backend, so it cannot be used for defaults and frontend sections.

The internal name specified for this server, which will appear in the log and warning messages; if "http-send-server-name" is set, it will also be added to the header of the request sent to this server

The IPv4 address of this server also supports the use of a resolvable hostname, but the hostname needs to be resolved to the corresponding IPv4 address at startup

[: port]: specifies the destination port to which the connection request is sent to this server, which is optional; if not set, the same phase port as the client request will be used

[param*]: a series of parameters set for this server. There are many parameters available. For details, please refer to the official documentation. Here are only a few commonly used parameters.

Server or default server parameters:

Backup: set as a standby server, and no other server in the load balancing scenario can be used to enable this server

Check: initiates a health check on this server, which can be more finely set with additional parameters, such as:

Inter: sets the time interval for health check in milliseconds, with a default of 2000. You can also use fastinter and downinter to optimize this delay based on server-side status.

Rise: set the number of times that a certain offline server needs to be checked successfully when it changes from offline to normal in the health check

Fall: confirm the number of times server needs to be checked for transition from normal state to unavailable state

Cookie: sets the cookie value for the specified server, the value specified here will be checked when the inbound request is made, and the server selected for this value for the first time will be selected in subsequent requests for the purpose of implementing persistent connections

Maxconn: specifies the maximum number of concurrent connections accepted by this server; if the number of connections sent 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

Haproxy has n processes, each supporting m connections, and the backend has x servers, each supporting a maximum of y connections, then tcp listener port will be started

Local2.* / var/log/haproxy.log

[root@node1 haproxy] # service rsyslog restar

[root@LB haproxy] # vim haproxy.cfg

Log 127.0.0.1 local2-> add this line on the global side

The simplest configuration of a http service

The code is as follows:

Global

Log 127.0.0.1 local2

Chroot / var/lib/haproxy

Pidfile / var/run/haproxy.pid

Maxconn 4000

User haproxy

Group haproxy

Daemon

Stats socket / var/lib/haproxy/stats

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

Frontend webser # webser is the name

Option forwardfor

Bind *: 80

Default_backend app

Backend app

Balance roundrobin # hold roundrobin algorithm

Server app1 192.168.1.111:80 check

Server app2 192.168.1.112:80 check

The output Mechanism of haproxy Statistics Page

The code is as follows:

Frontend webser

Log 127.0.0.1 local3

Option forwardfor

Bind *: 80

Default_backend app

Backend app

Cookie node insert nocache

Balance roundrobin

Server app1 192.168.1.111:80 check cookie node1 intval 2 rise 1 fall 2

Server app2 192.168.1.112:80 check cookie node2 intval 2 rise 1 fall 2

Server backup 127.0.0.1:8010 check backup

Listen statistics

Bind *: 8009 # Custom listening Port

Stats enable # enables statistical reporting based on the default settings when the program is compiled

Stats auth admin:admin # user name and password settings on the statistics page

Stats uri / admin?stats # URL of custom statistics page, default is / haproxy?stats

Stats hide-version # hides the version information of HAProxy on the statistics page

Stats refresh 30s # automatic refresh time of statistics page

Stats admin if TRUE # do the management function if the authentication is passed, and you can manage the back-end server

Prompt text on password box of stats realm Hapadmin # statistics page. Default is Haproxy\ Statistics

Examples of static and dynamic separation:

The code is as follows:

Frontend webservs

Bind *: 80

Acl url_static path_beg-I / static / images / javascript / stylesheets

Acl url_static path_end-I .jpg .gif .png .css .js .html

Acl url_php path_end-I. php

Acl host_static hdr_beg (host)-I img. Imgs. Video. Videos. Ftp. Image. Download.

Use_backend static if url_static or host_static

Use_backend dynamic if url_php

Default_backend dynamic

Backend static

Balance roundrobin

Server node1 192.168.1.111:80 check maxconn 3000

Backend dynamic

Balance roundrobin

Server node2 192.168.1.112:80 check maxconn 1000

Complete example of http server configuration

The code is as follows:

#-

# 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

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 30000

Listen stats

Mode http

Bind 0.0.0.0:1080

Stats enable

Stats hide-version

Stats uri / haproxyadmin?stats

Stats realm Haproxy\ Statistics

Stats auth admin:admin

Stats admin if TRUE

Frontend http-in

Bind *: 80

Mode http

Log global

Option httpclose

Option logasap # logs without waiting for the end of the response, which means logging in advance. Generally, the log records the response time, which does not record the response time.

Option dontlognull # does not record empty information

Capture request header Host len 20 # record the first 20 characters of the request header

Capture request header Referer len 60 # referer jump reference, which is the upper level

Default_backend servers

Frontend healthcheck

Bind: 1099 # defines an external detection mechanism

Mode http

Option httpclose

Option forwardfor

Default_backend servers

Backend servers

Balance roundrobin

Server websrv1 192.168.1.111:80 check maxconn 2000

Server websrv2 192.168.1.112:80 check maxconn 2000

Configuration example of load balancer MySQL service

The code is as follows:

#-

# 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

Defaults

Mode tcp

Log global

Option httplog

Option dontlognull

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 600

Listen stats

Mode http

Bind 0.0.0.0:1080

Stats enable

Stats hide-version

Stats uri / haproxyadmin?stats

Stats realm Haproxy\ Statistics

Stats auth admin:admin

Stats admin if TRUE

Frontend mysql

Bind *: 3306

Mode tcp

Log global

Default_backend mysqlservers

Backend mysqlservers

Balance leastconn

Server dbsrv1 192.168.1.111:3306 check port 3306 intval 2 rise 1 fall 2 maxconn 300

Server dbsrv2 192.168.1.112:3306 check port 3306 intval 2 rise 1 fall 2 maxconn 300

Thank you for your reading, the above is the content of "how to fully install and use agent software HAProxy on CentOS". After the study of this article, I believe you have a deeper understanding of how to fully install and use agent software HAProxy on CentOS, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 273

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report