- Simple Load Balancing with DNS on Linux
- Round-Robin DNS
- Subdomain Delegation and Round-Robin
- 10 Open Source Load Balancer for HA and Improved Performance
- Seesaw
- LoadMaster by KEMP
- HAProxy
- ZEVENET
- Neutrino
- Balance
- Nginx
- Traefik
- Gobetween
- Отказоустойчивый кластер для балансировки нагрузки
- Договоримся о терминах:
- Что потребуется:
- Используемые технологии:
- КОНЦЕПЦИЯ
- РЕАЛИЗАЦИЯ:
- ТЕСТИРОВАНИЕ:
- ПОСЛЕСЛОВИЕ:
Simple Load Balancing with DNS on Linux
When you have server back ends built of multiple servers, such as clustered or mirrowed web or file servers, a load balancer provides a single point of entry. Large busy shops spend big money on high-end load balancers that perform a wide range of tasks: proxy, caching, health checks, SSL processing, configurable prioritization, traffic shaping, and lots more.
But you don’t want all that. You need a simple method for distributing workloads across all of your servers and providing a bit of failover and don’t care whether it is perfectly efficient. DNS round-robin and subdomain delegation with round-robin provide two simple methods to achieve this.
DNS round-robin is mapping multiple servers to the same hostname, so that when users visit foo.example.com multiple servers are available to handle their requests.
Subdomain delegation with round-robin is useful when you have multiple subdomains or when your servers are geographically dispersed. You have a primary nameserver, and then your subdomains have their own nameservers. Your primary nameserver refers all subdomain requests to their own nameservers. This usually improves response times, as the DNS protocol will automatically look for the fastest links.
Round-Robin DNS
Round-robin has nothing to do with robins. According to my favorite librarian, it was originally a French phrase, ruban rond, or round ribbon. Way back in olden times, French government officials signed grievance petitions in non-hierarchical circular, wavy, or spoke patterns to conceal whoever originated the petition.
Round-robin DNS is also non-hierarchical, a simple configuration that takes a list of servers and sends requests to each server in turn. It does not perform true load-balancing as it does not measure loads, and does no health checks, so if one of the servers is down, requests are still sent to that server. Its virtue lies in simplicity. If you have a little cluster of file or web servers and want to spread the load between them in the simplest way, then round-robin DNS is for you.
All you do is create multiple A or AAAA records, mapping multiple servers to a single host name. This BIND example uses both IPv4 and IPv6 private address classes:
Dnsmasq uses /etc/hosts for A and AAAA records:
Note that these examples are simplified, and there are multiple ways to resolve fully-qualified domain names, so please study up on configuring DNS.
Use the dig command to check your work. Replace ns.example.com with your name server:
That should display both IPv4 and IPv6 round-robin records.
Subdomain Delegation and Round-Robin
Subdomain delegation combined with round-robin is more work to set up, but it has some advantages. Use this when you have multiple subdomains or geographically-dispersed servers. Response times are often quicker, and a down server will not respond, so clients will not get hung up waiting for a reply. A short TTL, such as 60 seconds, helps this.
This approach requires multiple name servers. In the simplest scenario, you have a primary name server and two subdomains, each with its own name server. Configure your round-robin entries on the subdomain servers, then configure the delegations on your primary server.
In BIND on your primary name server, you’ll need at least two additional configurations, a zone statement, and A/AAAA records in your zone data file. The delegation looks something like this on your primary name server:
Then each of the subdomain servers have their own zone files. The trick here is for each server to return its own IP address. The zone statement in named.conf is the same on both servers:
Then the data files are the same, except that the A/AAAA records use the server’s own IP address. The SOA (start of authority) refers to the primary name server:
Next, make your round-robin entries on the subdomain name servers, and you’re done. Now you have multiple name servers handling requests for your subdomains. Again, BIND is complex and has multiple ways to do the same thing, so your homework is to ensure that your configuration fits with the way you use it.
Subdomain delegations are easier in Dnsmasq. On your primary server, add lines like this in dnsmasq.conf to point to the name servers for the subdomains:
Then configure round-robin on the subdomain name servers in /etc/hosts .
For way more details and help, refer to these resources:
Learn more about Linux through the free “Introduction to Linux” course from The Linux Foundation and edX.
Источник
10 Open Source Load Balancer for HA and Improved Performance
Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
One of the quickest and easiest ways to setup application high-availability and improve performance is to implement the load balancer (LB).
On high-level, there are three types of load balancer.
A hardware load balancer is a dedicated appliance to provide load distribution, and it’s relevant features. Some of the popular LB hardware vendors are:
They are expensive but give you full control.
Cloud load balancer is trending more than ever.
Using cloud LB is one of the affordable ways to enjoy full features without investing in a hardware appliance. You pay for what you use. The following are some of the known cloud LB.
You can get it started from as low as $20 per month.
And the last one software-based where you install, manage and configure LB software by yourself. This can be either commercial or open-source/free.
If you don’t have a budget or would like to explore free solution load balancer then below will help you.
Seesaw
Used by Google, a reliable Linux-based virtual load balancer server to provide necessary load distribution in the same network.
Seesaw is developed in Go language and works well on Ubuntu/Debian distro. It supports anycast, DSR (direct server return) and requires two Seesaw nodes. They can be either physical or virtual.
Worth mentioning that Seesaw works with layer four networks, so if you are looking for layer seven load balancing then you may want to explore other option.
LoadMaster by KEMP
A FREE advanced application delivery controller by KEMP is supported on all major hypervisor. You can either download and use it in your data center or deploy in cloud DC like AWS or Azure.
It’s free but offers a commercial level of features including below.
- Layer 4 load balancing for TCP/UDP using round-robin or least connection algorithms
- Layer 7 balancing
- Inbuilt web application firewall (WAF)
- Inbuilt intrusion prevention engine (IPS)
- True global server load balancing, it supports multi-site
- Caching, content compression, content switching
- Web cookie persistence
- IPSec tunneling
KEMP LB is used by some of the big brands like Apple, Sony, JP Morgan, Audi, Hyundai, etc. Free edition provides sufficient features; however, if you need more, you can check out their commercial license.
If you or organization decide to explore KEMP LB and need some online training, then you can refer to this online course by Mike Walton.
HAProxy
One of the popular one out there in the market to provide high-availability, proxy, TCP/HTTP load-balancing. HAProxy is used by some of the reputed brands in the world, like below.
Some of the worth mentioning features are.
- Support IPv6 and UNIX socket
- Deflate & Gzip compression
- Health-check
- Source-based session stickiness
- Inbuilt statistics reporting (checkout demo)
As you may expect HAProxy got enterprise edition, hardware & virtual appliance.
The best way to know about HAProxy is to try them. Community edition comes with tons of features, and they are FREE anyway.
ZEVENET
Zevenet support L3, L4, and L7. It’s available as source code, IOS image and in a docker repository.
It supports advanced health-check monitoring, so faulty server/services are out of operation quickly to provide the seamless user experience. Zevenet formerly known as Zen works well with a TCP based protocol like FTP, SIP, SSL, HTTP, etc.
If you are looking Zevenet hosting then you may try Kamatera.
Neutrino
Neutrino is used by eBay and built using Scala & Netty. It supports least-connection and round-robin algorithms with the following switching features.
- Using canonical names
- Context-based
- L4 using TCP port numbers
Neutrino is tested to handle 300+ requests per seconds throughput on 2-core VM. If you are comparing with HAProxy, then one major advantage of using Neutrino is L7 switching.
But as always, try both and see what works the best for your environment.
Balance
Balance by In lab networks is a TCP proxy round-robin LB which supports IPv6 in the listening side. This means you can have IPv4 on front-end and IPv6 on the back-end.
It got all the basic LB features.
Pen is tested on Linux, FreeBSD, HP-UX, Solaris, Windows but no reason it shouldn’t work on another Unix distro. It supports UDP and TCP based protocols like HTTP, SNMP, DNS, etc.
Some of the features include the following along with basic one.
- GeoIP filter
- SSL termination
- IPv4 & IPv6 compatibility
Nginx
I know what you might be thinking. Nginx is a web server, proxy server, etc. But open source Nginx does support a basic level of content switching & request routing distribution across multiple servers.
However, Nginx Plus edition is much more than that.
Nginx Plus is an all-in-one web application delivery solution including load balancing, content caching, web server, WAF, monitoring, etc. It provides high-performance load balancer solution to scale applications to serve millions of request per seconds.
Traefik
A modern and fast HTTP reserve proxy and LB built with GO. Traefik support multiple back-end services Amazon ECS, Docker, Kubernetes, Rancher, etc.
It supports Websockets, HTTP/2, auto SSL certificate renewal with Let’s encrypt, clean interface to manage and monitor the resources.
Gobetween
Gobetween is minimalistic yet powerful high-performance L4 TCP, TLS & UDP based load balancer.
It works on multiple platforms like Windows, Linux, Docker, Darwin and if interested you can build from source code. Balancing is done based on the following algorithms you choose in the configuration.
- IP hash
- World famous – round robin
- Least bandwidth
- Least connection
- Weight
Based on this benchmark, Gobetween is faster than HAProxy but not from Nginx.
If you are looking for modern L4 balancing solution with auto-discovery for the dynamic environment, then Gobetween seems promising. Give a try to see how it goes.
Conclusion
I hope above listed open source load balancer software helps you to choose one for your application. They are all FREE, so the best ways to find what works is by trying them.
If you are looking to learn new skills then try Pluralsight, more than 6000 video courses are available.
Источник
Отказоустойчивый кластер для балансировки нагрузки
Поговорим о горизонтальном масштабировании. Допустим, ваш проект вырос до размеров, когда один сервер не справляется с нагрузкой, а возможностей для вертикального роста ресурсов уже нет.
В этом случае дальнейшее развитие инфраструктуры проекта обычно происходит за счет увеличения числа однотипных серверов с распределением нагрузки между ними. Такой подход не только позволяет решить проблему с ресурсами, но и добавляет надежности проекту — при выходе из строя одного или нескольких компонентов его работоспособность в целом не будет нарушена.
Большую роль в этой схеме играет балансировщик — система, которая занимается распределением запросов/трафика. На этапе ее проектирования важно предусмотреть следующие ключевые требования:
- Отказоустойчивость. Нужно как минимум два сервера, которые одновременно занимаются задачей распределения запросов/трафика. Без явного разделения ролей на ведущего и резервного.
- Масштабирование. Добавление новых серверов в систему должно давать пропорциональную прибавку в ресурсах.
Фактически, это описание кластера, узлами которого являются серверы-балансеры.
В этой статье мы хотим поделиться рецептом подобного кластера, простого и неприхотливого к ресурсам, концепцию которого успешно применяем в собственной инфраструктуре для балансировки запросов к серверам нашей панели управления, внутреннему DNS серверу, кластеру Galera и разнообразными микросервисам.
Договоримся о терминах:
— Серверы, входящие в состав кластера, будем называть узлами или балансерами.
— Конечными серверами будем называть хосты, на которые проксируется трафик через кластер.
— Виртуальным IP будем называть адрес, “плавающий” между всеми узлами, и на который должны указывать имена сервисов в DNS.
Что потребуется:
— Для настройки кластера потребуется как минимум два сервера (или вирт.машины) с двумя сетевыми интерфейсами на каждом.
— Первый интерфейс будет использоваться для связи с внешним миром. Здесь будут настроены реальный и виртуальный IP адреса.
— Второй интерфейс будет использоваться под служебный трафик, для общения узлов друг с другом. Здесь будет настроен адрес из приватной (“серой”) сети 172.16.0.0/24.
Вторые интерфейсы каждого из узлов должны находиться в одном сегменте сети.
Используемые технологии:
VRRP, Virtual Router Redundancy Protocol — в контексте этой статьи, реализация «плавающего» между узлами кластера виртуального IP адреса. В один момент времени такой адрес может быть поднят на каком-то одном узле, именуемом MASTER. Второй узел называется BACKUP. Оба узла постоянно обмениваются специальными heartbeat сообщениями. Получение или неполучение таких сообщений в рамках заданных промежутков дает основания для переназначения виртуального IP на “живой” сервер. Более подробно о протоколе можно прочитать здесь.
LVS, Linux Virtual Server — механизм балансировки на транспортном/сеансовом уровне, встроенный в ядро Linux в виде модуля IPVS. Хорошее описание возможностей LVS можно найти здесь и здесь.
Суть работы сводится к указанию того, что есть определенная пара “IP + порт” и она является виртуальным сервером. Для этой пары назначаются адреса реальных серверов, ответственных за обработку запросов, задается алгоритм балансировки, а также режим перенаправления запросов.
В нашей системе мы будем использовать Nginx как промежуточное звено между LVS и конечными серверами, на которые нужно проксировать трафик. Nginx будет присутствовать на каждом узле.
Для настроек VRRP и взаимодействия с IPVS будем использовать демон Keepalived, написанный в рамках проекта Linux Virtual Server.
КОНЦЕПЦИЯ
Система будет представлять собой связку из двух независимых друг от друга равнозначных узлов-балансеров, объединенных в кластер средствами технологии LVS и протокола VRRP.
Точкой входа для трафика будет являться виртуальный IP адрес, поднятый либо на одном, либо на втором узле.
Поступающие запросы LVS перенаправляет к одному из запущенных экземпляров Nginx — локальному или на соседнем узле. Такой подход позволяет равномерно размазывать запросы между всеми узлами кластера, т.е. более оптимально использовать ресурсы каждого балансера.
Работа Nginx заключается в проксировании запросов на конечные сервера. Начиная с версии 1.9.13 доступны функции проксирования на уровне транспортных протоколов tcp и udp.
Каждый vhost/stream будет настроен принимать запросы как через служебный интерфейс с соседнего балансера так и поступающие на виртуальный IP. Причем даже в том случае, если виртуальный IP адрес физически не поднят на данном балансере (Keepalived назначил серверу роль BACKUP).
Таким образом, схема хождения трафика в зависимости от состояния балансера (MASTER или BACKUP) выглядит так:
- запрос приходит на виртуальный IP. IPVS маршрутизирует пакет на локальный сервер;
- поскольку локальный Nginx слушает в том числе виртуальный IP, он получает запрос;
- согласно настройкам проксирования для данного виртуального IP Nginx отправляет запрос одному из перечисленных апстримов;
- полученный ответ отправляется клиенту.
- запрос приходит на виртуальный IP. IPVS маршрутизирует пакет на соседний сервер;
- на соседнем балансере этот виртуальный IP не поднят. Поэтому dst_ip в пакете нужно заменить на соответствующий серый IP из сети текущего балансера. Для этого используется DNAT;
- после этого локальный Nginx получает запрос на серый IP адрес;
- согласно настройкам проксирования для данного виртуального IP Nginx отправляет запрос одному из перечисленных апстримов;
- полученный ответ отправляется клиенту напрямую с src_ip равным виртуальному IP (при участии conntrack)
РЕАЛИЗАЦИЯ:
В качестве операционной системы будем использовать Debian Jessie с подключенными backports репозиториями.
Установим на каждый узел-балансер пакеты с необходимым для работы кластера ПО и сделаем несколько общесистемных настроек:
На интерфейсе eth1 настроим адреса из серой сети 172.16.0.0/24 :
Виртуальный IP адрес прописывать на интерфейсе eth0 не нужно. Это сделает Keepalived.
В файл /etc/sysctl.d/local.conf добавим следующие директивы:
Первая включает возможность слушать IP, которые не подняты локально (это нужно для работы Nginx). Вторая включает автоматическую защиту от DDoS на уровне балансировщика IPVS (при нехватке памяти под таблицу сессий начнётся автоматическое вычищение некоторых записей). Третья увеличивает размер conntrack таблицы.
В /etc/modules включаем загрузку модуля IPVS при старте системы:
Параметр conn_tab_bits определяет размер таблицы с соединениями. Его значение является степенью двойки. Максимально допустимое значение — 20.
Кстати, если модуль не будет загружен до старта Keepalived, последний начинает сегфолтиться.
Теперь перезагрузим оба узла-балансера. Так мы убедимся, что при старте вся конфигурация корректно поднимется.
Общие настройки выполнены. Дальнейшие действия будем выполнять в контексте двух задач:
- Балансировка http трафика между тремя веб-серверами;
- Балансировка udp трафика на 53 порт двух DNS серверов.
Вводные данные:
- В качестве виртуального IP адреса будем использовать 192.168.0.100 ;
- У веб-серверов будут адреса 192.168.0.101 , 192.168.0.102 и 192.168.0.103 соответственно их порядковым номерам;
- У DNS серверов 192.168.0.201 и 192.168.0.202 .
Начнем с конфигурации Nginx.
Добавим описание секции stream в /etc/nginx/nginx.conf :
И создадим соответствующий каталог:
Настройки для веб-серверов добавим в файл /etc/nginx/sites-enabled/web_servers.conf
Настройки для DNS-серверов добавим в файл /etc/nginx/stream-enabled/dns_servers.conf
Далее остается сконфигурировать Keepalived (VRRP + LVS). Это немного сложнее, поскольку нам потребуется написать специальный скрипт, который будет запускаться при переходе узла-балансера между состояниями MASTER/BACKUP.
Все настройки Keepalived должны находиться в одном файле — /etc/keepalived/keepalived.conf . Поэтому все нижеследующие блоки с конфигурациями VRRP и LVS нужно последовательно сохранить в этом файле.
Скрипт, который упоминался выше — /usr/local/bin/nat-switch . Он запускается каждый раз, когда у текущего VRRP инстанса меняется состояние. Его задача заключается в том, чтобы балансер, находящийся в состоянии BACKUP, умел корректно обработать пакеты, адресованные на виртуальный IP. Для решения этой ситуации используются возможности DNAT. А именно, правило вида:
При переходе в состояние MASTER, скрипт удаляет это правило.
Здесь можно найти вариант скрипта nat-switch , написанный для данного примера.
Настройки LVS для группы веб-серверов:
Настройки LVS для группы DNS-серверов:
В завершении перезагрузим конфигурацию Nginx и Keepalived:
ТЕСТИРОВАНИЕ:
Посмотрим как балансировщик распределяет запросы к конечным серверам. Для этого на каждом из веб-серверов создадим index.php с каким-нибудь простым содержимым:
И сделаем несколько запросов по http к виртуальному IP 192.168.0.100 :
Если в процессе выполнения этого цикла посмотреть на статистику работы LVS (на MASTER узле), то мы можем увидеть следующую картину:
Здесь видно как происходит распределение запросов между узлами кластера: есть два активных соединения, которые обрабатываются в данный момент и 6 уже обработанных соединений.
Статистику по все соединениям, проходящим через LVS, можно посмотреть так:
Здесь, соответственно, видим то же самое: 2 активных и 6 неактивный соединений.
ПОСЛЕСЛОВИЕ:
Предложенная нами конфигурация может послужить отправным пунктом для проектирования частного решения под конкретный проект со своими требованиями и особенностями.
Если у вас возникли вопросы по статье или что-то показалось спорным — пожалуйста, оставляйте свои комментарии, будем рады обсудить.
Источник