Пример HAProxy
HAProxy является бесплатным балансировщиком нагрузки, который работает в Linux. Это мощное средство, поддерживающее готовые к применению возможности мониторинга.
Дополнительные сведения о его конфигурации см. в документе https://cbonte.github.io/haproxy-dconv/2.0/configuration.html (на английском языке)
Глобальные настройки
Глобальные настройки применяются к интерфейсным и внутренним серверам и обычно могут игнорироваться.
Например:
#--------------------------------------------------------------------- #
Global settings
#---------------------------------------------------------------------
global
# setup logging and force level to debug. Logs require rsyslog be setup.
chroot /var/lib/haproxy
log /dev/log local0 debug
# maximum number of connections allowed
maxconn 10000
# turn on stats unix socket
stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
stats timeout 30s
# user and group haproxy will run as
user haproxy
group haproxy
Настройки по умолчанию
Эти настройки предназначены для конфигураций по умолчанию для внутренних серверов.
log
Используйте ведение журнала, сконфигурированное в глобальных настройках.
mode
Определяет способ анализа запросов. В этом примере используется обработка HTTP.
option
Например:
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
default-server init-addr last,libc,none
log global
mode http
option httplog
option redispatch
option forwardfor
timeout connect 10s
timeout client 60s
timeout server 60s
timeout tunnel 1h
Интерфейсные настройки
Это интерфейс, через который проходят все приложения. В нем содержатся правила маршрутизации, определяющие, какой внутренний сервер используется для обработки входящего запроса.
bind
Указывает порт, на котором будут приниматься входящие запросы.
capture
Включает файл cookie идентификатора сессии в ведение журнала HTTP-запросов HAProxy.
acl
Создает переменную на основе проверяемого условия. Например, -i -m beg <string> проверяет URI, начинающийся с <string>.
use_backend
В зависимости от значения true или false для переменных выполняется маршрутизация к определенной группе внутренних серверов.
default
Используемый внутренний сервер, если он не соответствует другим правилам.
Например:
#---------------------------------------------------------------------
# FrontEnd Configuration
#---------------------------------------------------------------------
frontend ft_web
bind *:8080 name web
# log the session cookie if passed
capture cookie JSESSIONID= len 32
## path based routing to connection server
acl path_cxserver path -i -m beg /Thingworx/WS
acl path_tunnelserver path -i -m beg /Thingworx/WSTunnelServer
acl path_tunnelclient path -i -m beg /Thingworx/WSTunnelClient
use_backend cxserver if path_cxserver or path_tunnelserver or path_tunnelclient

# default traffic to platform
default_backend platform
Пример для ThingWorx Flow
#---------------------------------------------------------------------
# FrontEnd Configuration
#---------------------------------------------------------------------
frontend ft_web
bind *:8443 ssl crt /certs/haproxy.pem name sslweb
# log the session cookie if passed
capture cookie JSESSIONID= len 32
##path based routing to ThingWorx Flow
acl p_flow1 path -i -m beg /Thingworx/Composer/apps/flow
acl p_flow2 path -i -m beg /Thingworx/Flow
acl p_flow3 path -i -m beg /Thingworx/Triggers
acl p_flow4 path -i -m beg /Thingworx/Lookups
acl p_flow5 path -i -m beg /Thingworx/Oauths
acl p_flow6 path -i -m beg /Thingworx/Subsystems/EventProcessingSubsystem/Subscriptions
acl p_flow7 path -i -m beg /enterprise/v1/fetchconfig
use_backend flow if p_flow1 or p_flow2 or p_flow3 or p_flow4 or p_flow5 or p_flow6 or p_flow7
Настройки платформы внутренних серверов
Внутренними называют группу серверов, которые могут обрабатывать запросы, передаваемые из интерфейсных серверов и любых конкретных конфигураций.
balance
Алгоритм балансировки нагрузки. По умолчанию выполняется циклический обход доступных серверов для следующего доступного соединения.
cookie
Вставляет файл cookie, используемый балансировщиком нагрузки для маршрутизации будущих запросов к тому же серверу.
Например:
#---------------------------------------------------------------------
# BackEnd Platform Configuration
#---------------------------------------------------------------------
backend platform
balance roundrobin
# sticky sessions
cookie SERVER insert indirect nocache
http-request set-header X-Forwarded-Port %[dst_port]
http-request add-header X-Forwarded-Proto https if { ssl_fc }
# health check
option httpchk GET /Thingworx/health
# configure platform instances
server platform1 10.0.10.10:8080 check inter 1000 fastinter 1000 cookie twx1
server platform2 10.0.10.11:8080 check inter 1000 fastinter 1000 cookie twx2
Пример для ThingWorx Flow
#---------------------------------------------------------------------
# BackEnd Flow Configuration
#---------------------------------------------------------------------
backend flow
balance source

option forwardfor
http-request set-header X-Forwarded-Port %[dst_port]
http-request add-header X-Forwarded-Proto https if { ssl_fc }

# configure flow instances
server nginx {nginx_ip}:443 check ssl verify none
Настройки сервера внутреннего соединения
Пример
#---------------------------------------------------------------------
# BackEnd Connection Server Configuration
#---------------------------------------------------------------------
backend cxserver
balance source
#hash-type consistent
option httpchk GET /
# configure connection server instances
server cxserver1 10.0.10.20:8080 check port 9009
server cxserver2 10.0.10.21:8080 check port 9009
Мониторинг
HAProxy имеет пользовательский интерфейс мониторинга, который может использоваться для просмотра потока трафика. Можно сконфигурировать порт входящего трафика и дополнительные учетные данные.
#---------------------------------------------------------------------
#HAProxy Monitoring Config
#---------------------------------------------------------------------
listen stats
bind *:1936
mode http
option forwardfor
option httpclose
stats enable
stats uri /
stats refresh 5s
stats show-legends
stats realm Haproxy\ Statistics
Полный пример
#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
# setup logging and force level to debug. Logs require rsyslog be setup.
chroot /var/lib/haproxy
log /dev/log local0 debug
# maximum number of connections allowed
maxconn 10000
# turn on stats unix socket
stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
stats timeout 30s
# user and group haproxy will run as
user haproxy
group haproxy
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
default-server init-addr last,libc,none
log global
mode http
option httplog
option redispatch
option forwardfor
timeout connect 10s
timeout client 60s
timeout server 60s
timeout tunnel 1h
#---------------------------------------------------------------------
# FrontEnd Configuration
#---------------------------------------------------------------------
frontend ft_web
bind *:8080 name web
# log the session cookie if passed
capture cookie JSESSIONID= len 32
## path based routing to connection server
acl path_cxserver path -i -m beg /Thingworx/WS
acl path_tunnelserver path -i -m beg /Thingworx/WSTunnelServer
acl path_tunnelclient path -i -m beg /Thingworx/WSTunnelClient
use_backend cxserver if path_cxserver or path_tunnelserver or path_tunnelclient
# default traffic to platform
default_backend platform
#---------------------------------------------------------------------
# BackEnd Platform Configuration
#---------------------------------------------------------------------
backend platform
balance roundrobin
# sticky sessions
cookie SERVER insert indirect nocache
http-request set-header X-Forwarded-Port %[dst_port]
http-request add-header X-Forwarded-Proto https if { ssl_fc }
# health check
option httpchk GET /Thingworx/health
# configure platform instances
server platform1 10.0.10.10:8080 check inter 1000 fastinter 1000" cookie twx1
server platform2 10.0.10.11:8080 check inter 1000 fastinter 1000" cookie twx2
#---------------------------------------------------------------------
# BackEnd Connection Server Configuration
#---------------------------------------------------------------------
backend cxserver
balance source
#hash-type consistent
option httpchk GET /
# configure connection server instances
server cxserver1 10.0.10.20:8080 check port 9009
server cxserver2 10.0.10.21:8080 check port 9009
#---------------------------------------------------------------------
#HAProxy Monitoring Config
#---------------------------------------------------------------------
listen stats
bind *:1936
mode http
option forwardfor
option httpclose
stats enable
stats uri /
stats refresh 5s
stats show-legends
stats realm Haproxy\ Statistics
Было ли это полезно?