Title: 🌀 HAProxy — Cheatsheet Group: Web Servers Icon: 🌀 Order: 5 # 🌀 HAProxy — Cheatsheet (EN / RU) ## Table of Contents - [Installation & Configuration](#installation--configuration) - [Core Concepts](#core-concepts) - [Configuration Sections](#configuration-sections) - [Global Section](#global-section) - [Defaults Section](#defaults-section) - [Frontend Section](#frontend-section) - [Backend Section](#backend-section) - [Listen Section](#listen-section) - [Load Balancing Algorithms](#load-balancing-algorithms) - [ACL & Routing](#acl--routing) - [SSL/TLS Configuration](#ssltls-configuration) - [Health Checks](#health-checks) - [Stick Tables & Rate Limiting](#stick-tables--rate-limiting) - [Caching](#caching) - [Logging](#logging) - [Runtime Management](#runtime-management) - [Production Scenarios](#production-scenarios) - [Quick Templates](#quick-templates) - [Troubleshooting](#troubleshooting) - [Logrotate Configuration](#logrotate-configuration--конфигурация-logrotate) --- ## Installation & Configuration ### Package Installation / Установка пакетов ```bash # Debian/Ubuntu sudo apt update && sudo apt install haproxy # Install HAProxy / Установить HAProxy # RHEL/CentOS/AlmaLinux sudo dnf install haproxy # Install HAProxy / Установить HAProxy sudo systemctl enable haproxy # Enable at boot / Автозапуск ``` ### Default Paths / Пути по умолчанию `/etc/haproxy/haproxy.cfg` — Main config / Основной конфиг `/run/haproxy.sock` — Runtime socket / Рантайм сокет `/run/haproxy.pid` — PID file / Файл PID `/var/log/haproxy.log` — Log file / Лог файл `/etc/haproxy/certs/` — SSL certificates / SSL сертификаты ### Service Control / Управление сервисом ```bash sudo systemctl start haproxy # Start service / Запустить сервис sudo systemctl stop haproxy # Stop service / Остановить сервис sudo systemctl restart haproxy # Restart service / Перезапустить сервис sudo systemctl reload haproxy # Reload config / Перечитать конфиг sudo systemctl status haproxy # Service status / Статус сервиса ``` ### Configuration Testing / Проверка конфигурации ```bash haproxy -c -f /etc/haproxy/haproxy.cfg # Test config / Проверка конфига haproxy -f /etc/haproxy/haproxy.cfg -c -db # Debug mode / Режим отладки ``` ### Zero-Downtime Reload / Reload без простоя ```bash # Validate config / Проверка конфига haproxy -c -f /etc/haproxy/haproxy.cfg # Reload (systemd) / Reload через systemd sudo systemctl reload haproxy # Manual reload / Ручной reload haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -sf $(cat /run/haproxy.pid) ``` ### Default Ports / Порты по умолчанию - **80** — HTTP (configurable in frontend) - **443** — HTTPS (configurable in frontend) - **8404** — Stats page (configurable) --- ## Core Concepts **EN:** HAProxy operates as: **input → rules → output** **RU:** HAProxy работает как: **вход → правила → выход** ### Mental Map / Ментальная карта * **global** — Process & OS: logs, master-worker, runtime socket / Процесс и ОС * **defaults** — Timeouts, log format, common options / Таймауты, общие опции * **frontend** — Input: `bind`, ACL, redirects, headers, backend choice / «Вход» * **backend** — Output: balancing, servers, health-checks, cache/compression / «Выход» * **listen** — Combined block (useful for stats) / Комбинированный блок --- ## Configuration Sections ### Global Section Global section defines process-level settings / Глобальный раздел определяет настройки процесса ```cfg global log /dev/log local0 # Syslog facility / Логирование в syslog chroot /var/lib/haproxy # Jail dir / Директория chroot pidfile /run/haproxy.pid # PID file / Файл PID maxconn 10000 # Max concurrent connections / Макс. соединений daemon # Run in background / Запуск как демон user haproxy # User / Пользователь group haproxy # Group / Группа master-worker # Graceful reload / Безразрывный перезапуск stats socket /run/haproxy.sock mode 660 level admin expose-fd listeners # Runtime socket / Управление через сокет nbthread 4 # Number of threads / Кол-во потоков (по ядрам CPU) tune.ssl.default-dh-param 2048 # DH param size / Размер ключа DH ssl-default-bind-options no-sslv3 no-tlsv10 no-tlsv11 # Disable weak TLS / Отключить слабые версии TLS ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:... # Allowed ciphers / Шифры ``` **Key Parameters:** - `log
` — Define syslog server / Указать syslog-сервер - `maxconn ` — Global connection limit / Глобальное ограничение соединений - `nbthread ` — Threads (recommended = CPU cores) / Потоки (= число ядер) - `master-worker` — Enables seamless reloads / Безразрывные перезапуски - `stats socket` — Enable runtime API / Включить runtime API --- ### Defaults Section Defaults section sets common settings for all proxies / Раздел defaults задает общие настройки ```cfg defaults mode http # default mode / Режим по умолчанию (http|tcp) log global # Use global logging / Использовать глобальный лог option httplog # HTTP log format / Лог в формате HTTP option dontlognull # Skip empty conns / Не логировать пустые соединения option http-keep-alive # Keep-Alive / Поддержка keep-alive option forwardfor if-none # Add X-Forwarded-For / Добавить IP клиента timeout connect 5s # Timeout to connect backend / Таймаут подключения timeout client 60s # Timeout client / Таймаут клиента timeout server 60s # Timeout server / Таймаут сервера retries 3 # Retry attempts / Кол-во повторных попыток default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions # Server defaults / Настройки проверки серверов ``` **Key Parameters:** - `mode http|tcp` — Operating mode / Режим работы - `option httplog` — Detailed HTTP log format / Подробный формат логов HTTP - `option forwardfor` — Add `X-Forwarded-For` header / Добавить заголовок с IP клиента - `timeout connect/client/server` — Connection timeouts / Таймауты соединений - `retries` — Retry attempts on failure / Повторные попытки при ошибке --- ### Frontend Section Frontend defines entry point for connections / Frontend определяет точку входа ```cfg frontend fe_http bind *:80 # Bind address:port / Адрес и порт mode http # Mode (http|tcp) / Режим работы default_backend bk_web # Default backend / Бэкенд по умолчанию # HTTP→HTTPS redirect / Редирект HTTP→HTTPS http-request redirect scheme https code 301 if !{ ssl_fc } # Add unique request ID / Добавить уникальный ID http-request set-header X-Request-ID %[unique-id] ``` **Key Parameters:** - `bind :` — Listening address and port / Адрес и порт для прослушивания - `default_backend` — Default backend pool / Бэкенд по умолчанию - `http-request` — Request rules (redirect, deny, set-header) / Правила обработки запросов --- ### Backend Section Backend defines server pool / Backend определяет пул серверов ```cfg backend bk_web balance roundrobin # Load balancing algo / Алгоритм балансировки server web1 :80 check # Server + health-check / Сервер с проверкой server web2 :80 check server web3 :80 check backup # Backup server / Резервный сервер ``` **Key Parameters:** - `balance` — Load balancing algorithm / Алгоритм балансировки - `server : [options]` — Define backend server / Определить сервер - `check` — Enable health-check / Включить проверку здоровья - `backup` — Use only if others fail / Использовать только при падении других --- ### Listen Section Listen combines frontend + backend / Listen объединяет frontend и backend ```cfg listen stats bind *:8404 # Bind port / Порт веб-интерфейса mode http # HTTP mode / Режим HTTP stats enable # Enable stats / Включить статистику stats uri /stats # URI / Путь к странице статистики stats auth : # Login / Авторизация stats refresh 5s # Auto-refresh / Автообновление ``` --- ## Load Balancing Algorithms ### Common Algorithms / Основные алгоритмы | Algorithm | Description (EN) | Description (RU) | Use Case | | :--- | :--- | :--- | :--- | | **roundrobin** | Sequentially distributes requests. Dynamic (can change weight on the fly). Default. | Последовательно распределяет запросы. Динамический (можно менять вес на лету). По умолчанию. | General purpose / Общее назначение | | **leastconn** | Selects server with fewest active connections. Recommended for long sessions (DB, WebSocket). | Выбирает сервер с наименьшим числом активных соединений. Рекомендуется для долгих сессий (БД, WebSocket). | Databases, long sessions / Базы данных, долгие сессии | | **source** | Hashes client IP. Ensures specific IP always hits the same server (unless server goes down). | Хеширует IP клиента. Гарантирует, что IP попадает на тот же сервер (если он доступен). | IP Persistence / Привязка по IP | | **uri** | Hashes the URI (path + query). Optimizes cache hit rates. | Хеширует URI (путь + запрос). Оптимизирует попадание в кэш. | Caching proxies / Кэширующие прокси | | **url_param** | Hashes a specific URL parameter. | Хеширует конкретный параметр URL. | Tracking, User ID / Трекинг, ID пользователя | | **hdr(name)** | Hashes a specific HTTP header (e.g., `hdr(User-Agent)`). | Хеширует конкретный HTTP заголовок (например, `User-Agent`). | Specialized routing / Специальная маршрутизация | | **random** | Randomly chooses a server. Consistent hashing available. | Случайный выбор сервера. Доступно консистентное хеширование. | Large farms / Большие фермы | ### Configuration Example / Пример конфигурации ```cfg backend bk_web # 1. Round Robin (Default) / По кругу (По умолчанию) balance roundrobin # 2. Least Connections (DBs) / Меньше всего соединений (БД) # balance leastconn # 3. Source IP Hash (Session stickiness) / Хеш по IP (Липкость сессии) # balance source # 4. URI Hash (Cache) / Хеш по URI (Кэш) # balance uri # hash-type consistent # Consistent hashing for cache / Консистентное хеширование для кэша # 5. URL Parameter / Параметр URL # balance url_param userid checkout ``` --- ## ACL & Routing Access Control Lists (ACLs) are the core of HAProxy's flexibility. They define conditions to route traffic, block requests, or modify headers. ACL - это основа гибкости HAProxy. Они определяют условия для маршрутизации трафика, блокировки запросов или изменения заголовков. ### 1. Basic Syntax / Базовый синтаксис `acl [flags] [operator] ...` * **acl_name**: Arbitrary name (e.g., `is_api`, `bad_ip`). / Произвольное имя. * **criterion**: What to check (e.g., `src`, `path`, `hdr`). / Что проверять. * **flags**: `-i` (ignore case), `-m` (match method). / Флаги: `-i` (без учета регистра). * **value**: Pattern to match. / Значение для проверки. ### 2. Logical Operators / Логические операторы * **AND**: Implicit (listing ACLs one after another). / Неявный (перечисление ACL подряд). * **OR**: `||` or `or`. / `||` или `or`. * **Negation (NOT)**: `!`. / Отрицание: `!`. ```cfg http-request deny if is_admin !is_internal_ip # Deny if admin AND NOT internal IP http-request deny if bad_bot || bad_referer # Deny if bad bot OR bad referer ``` ### 3. Common Matching Methods / Методы сравнения | Suffix | Meaning | Example | | :--- | :--- | :--- | | **(exact)** | Exact match / Точное совпадение | `path /api` | | **_beg** | Prefix match / Начало строки | `path_beg /api/` | | **_end** | Suffix match / Конец строки | `path_end .jpg` | | **_sub** | Substring match / Подстрока | `hdr_sub(User-Agent) Mozilla` | | **_reg** | Regular expression / Регулярное выражение | `path_reg ^/api/v[0-9]+/` | | **_dir** | Subdirectory match / Подпапка | `path_dir api` (matches `/api/foo`) | | **_dom** | Domain match / Домен | `hdr_dom(host) example.com` | ### 4. Common Criteria / Основные критерии | Criterion | Description (EN) | Description (RU) | | :--- | :--- | :--- | | **src** | Source IP address. | IP адрес источника. | | **path** | Request path (URI without query string). | Путь запроса (без query string). | | **url** | Full URL. | Полный URL. | | **method** | HTTP method (GET, POST, etc.). | HTTP метод. | | **hdr(name)** | specific HTTP header value. | Значение конкретного заголовка. | | **query** | Query string parameters. | Параметры строки запроса. | | **ssl_fc** | Returns true if connection is SSL/TLS. | Истина, если соединение SSL/TLS. | | **ssl_fc_sni** | SNI value sent by client. | Значение SNI от клиента. | | **dst_port** | Destination port. | Порт назначения. | ### 5. Detailed Examples / Подробные примеры ```cfg frontend fe_main bind *:443 ssl crt /etc/haproxy/certs/ # --- DEFINITIONS / ОПРЕДЕЛЕНИЯ --- # Path matching / Совпадение по пути acl is_api path_beg /api acl is_static path_end .jpg .png .css .js # Host matching / Совпадение по хосту acl is_admin_host hdr(host) -i admin.example.com # IP Whitelist / Белый список IP acl is_internal src 10.0.0.0/8 192.168.1.0/24 # User-Agent blocking / Блокировка по User-Agent acl is_bad_bot hdr_sub(User-Agent) -i curl wget python scan # Method check / Проверка метода acl is_post method POST # --- ACTIONS / ДЕЙСТВИЯ --- # 1. Block bad bots / Блокировка ботов http-request deny if is_bad_bot # 2. Protect Admin Area (Allow only internal IPs) / Защита админки # Deny if trying to access admin host AND NOT from internal IP http-request deny if is_admin_host !is_internal # 3. Routing / Маршрутизация use_backend bk_api if is_api use_backend bk_static if is_static use_backend bk_admin if is_admin_host # 4. Default / По умолчанию default_backend bk_www ``` --- ## SSL/TLS Configuration ### HTTPS Termination / Терминация HTTPS ```cfg frontend fe_https bind :443 ssl crt /etc/haproxy/certs/ alpn h2,http/1.1 # Enable TLS + HTTP/2 / Включение TLS и HTTP/2 # HSTS header / HSTS заголовок http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" default_backend bk_app ``` ### HTTP → HTTPS Redirect / Редирект HTTP→HTTPS ```cfg frontend fe_http bind :80 http-request redirect scheme https code 301 unless { ssl_fc } ``` ### TLS Passthrough (L4) / Сквозной TLS ```cfg defaults mode tcp # TCP mode / TCP режим option tcplog # TCP log format / Лог TCP frontend fe_tls_passthrough bind :443 tcp-request inspect-delay 5s tcp-request content accept if { req_ssl_hello_type 1 } use_backend bk_tls_www if { req_ssl_sni -i } # Route by SNI / Роутинг по SNI default_backend bk_tls_www backend bk_tls_www server w1 :443 check ``` ### SSL Best Practices / Лучшие практики SSL ```cfg global tune.ssl.default-dh-param 2048 ssl-default-bind-options no-sslv3 no-tlsv10 no-tlsv11 ssl-default-bind-ciphers HIGH:!aNULL:!MD5 frontend fe_secure bind :443 ssl crt /etc/haproxy/certs/ alpn h2,http/1.1 http-response set-header Strict-Transport-Security "max-age=31536000" ``` --- ## Health Checks Health checks determine if a server is available to receive traffic. Проверки здоровья определяют, доступен ли сервер для приема трафика. ### 1. Active Health Checks (Polling) / Активные проверки (Опрос) The `check` keyword enables active periodic checks. HAProxy probes the server. Ключевое слово `check` включает активные периодические проверки. HAProxy опрашивает сервер. ```cfg backend bk_pool # Basic TCP check / Базовая TCP проверка server web1 192.168.1.10:80 check inter 2s rise 3 fall 2 ``` **Parameters / Параметры:** * `check`: Enables health checking. * `inter