Round robin dns linux
Добрый день! Уважаемые читатели и гости одного из крупнейших IT блогов на просторах рунета Pyatilistnik.org. Продолжаем с вами усовершенствовать свои навыки и знания в сфере системного администрирования. В предыдущей статье мы с вами разобрали основные понятия DNS сервера и его компонентов. Сегодня мы более подробно разберем, одну из его полезнейших вещей, которую очень часто используют, например на RDS фермах, или различных балансировщиках. Речь пойдет про функционал DNS Round Robin, рассмотрим его настройку и его применение.
Теория
Статья описывает одну из технологий балансировки нагрузки, которая может быть реализована средствами DNS. Для перевода имени хоста в IP-адрес клиент DNS направляет серверу DNS рекурсивный запрос (т.е. запрос, на который сервер DNS возвращает клиенту либо ответ с IP адресом, либо ответ с ошибкой).
В подавляющем большинстве случаев в зонах DNS содержится только один IP адрес, соответствующий тому или иному имени хоста. А какой IP адрес будет возвращать клиенту сервер DNS, если зона содержит несколько записей типа A для одного и того же имени? Ответ простой: сервер DNS всегда возвращает клиенту все IP адреса, соответствующие запрашиваемому имени. А дальше клиент пытается связаться с первым IP адресом в списке и, если он не будет найден, делает попытку связаться со вторым адресом и т.д.
Предположим, у меня есть несколько зеркальных веб-сайтов по имени www.gorbunov.pro, расположенных на разных площадках и имеющих IP адреса 20.0.0.1, 30.0.0.1 и 40.0.0.1.
В ответ на рекурсивный запрос клиента об имени www.gorbunov.pro сервер DNS вернет клиенту весь набор записей из зоны:
www.gorbunov.pro 20.0.0.1
www.gorbunov.pro 30.0.0.1
www.gorbunov.pro 40.0.0.1
Поскольку адрес 20.0.0.1 идет первым в списке, клиент всегда будет пытаться связаться именно с сайтом по адресу 20.0.0.1. Получается, что сайты 30.0.0.1 и 40.0.0.1 используются только как пассивный резерв. До тех пор, пока «жив» сайт по адресу 20.0.0.1, сайты 30.0.0.1 и 40.0.0.1 не получат от клиента ни одного запроса.
Как сделать, чтобы запросы “доставались” всем хостам? Ответ простой: настроить на сервере DNS функцию Round robin.
При включенной функции Round robin сервер DNS постоянно «перемешивает» ответы клиентам, поэтому на первый запрос клиента DNS об имени www.gorbunov.pro сервер DNS вернет ответ
www.gorbunov.pro 20.0.0.1
www.gorbunov.pro 30.0.0.1
www.gorbunov.pro 40.0.0.1
На второй запрос от клиента или от другого сервера DNS будет возвращен ответ
www.gorbunov.pro 30.0.0.1
www.gorbunov.pro 40.0.0.1
www.gorbunov.pro 20.0.0.1
На третий запрос будет ответ
www.gorbunov.pro 40.0.0.1
www.gorbunov.pro 20.0.0.1
www.gorbunov.pro 30.0.0.1
В результате мы получаем динамическую балансировку запросов клиентов между несколькими хостами.
Практика
____________________________________________________________________________________
Проверка работы DNS Round robin
В Windows Server опция Enable round robin включена по умолчанию. Достаточно в консоли DNS Manager открыть свойства DNS сервера и посмотреть вкладку Advanced.
Что такое DNS Round robin и как он работает-01
Для практической проверки функционала DNS Round robin создаем зону gorbunov.pro и добавляем в нее три записи для хоста www.
Что такое DNS Round robin и как он работает-02
Если вы попробуете теперь “попинговать” хост www.gorbunov.pro, то с удивлением обнаружите, что клиент все время отправляет пакеты на адрес 20.0.0.1 (выделено красным). Понятно, что ответа от хоста нет, но и DNS Round robin не работает!
Pinging www.gorbunov.pro [20.0.0.1] with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Ping statistics for 20.0.0.1:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
C:\>ping www.gorbunov.pro
Pinging www.gorbunov.pro [20.0.0.1] with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Ping statistics for 20.0.0.1:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
C:\>
Анализ кэша DNS на стороне клиента дает следующий результат:
C:\>ipconfig /displaydns
Windows IP Configuration
www.gorbunov.pro
—————————————-
Record Name . . . . . : www.gorbunov.pro
Record Type . . . . . : 1
Time To Live . . . . : 3567
Data Length . . . . . : 4
Section . . . . . . . : Answer
A (Host) Record . . . : 20.0.0.1
Record Name . . . . . : www.gorbunov.pro
Record Type . . . . . : 1
Time To Live . . . . : 3567
Data Length . . . . . : 4
Section . . . . . . . : Answer
A (Host) Record . . . : 30.0.0.1
Record Name . . . . . : www.gorbunov.pro
Record Type . . . . . : 1
Time To Live . . . . : 3567
Data Length . . . . . : 4
Section . . . . . . . : Answer
A (Host) Record . . . : 40.0.0.1
C:\>
Теперь становится понятно, почему мы “пингуем” один и тот же хост 20.0.0.1. Сервер DNS возвращает клиенту все записи из зоны с указанием времени кэширования, равным по умолчанию 1 часу (или 3600 секундам). Поэтому до истечения времени кэширования (TTL – Time To Live) клиент больше не направляет к серверу DNS никаких новых запросов.
Сброс кэша командой ipconfig / flushdns и новая команда
ping www.gorbunov.pro приводят, наконец к желаемому результату.C:\>ipconfig /flushdns
Windows IP Configuration
Successfully flushed the DNS Resolver Cache.
C:\>ping www.gorbunov.pro –n 1
Pinging www.gorbunov.pro [30.0.0.1] with 32 bytes of data:
Request timed out.
Теперь ясно, что для правильной работы DNS Round robin потребуется изменение параметров кэширования, чтобы клиенты постоянно получали обновленный список с “перемешанными” записями.
Настройка времени кэширования ответов DNS
Возможные варианты:
постоянный сброс кэша на стороне клиента (плохой вариант);
установка времени кэширования, равное нулю, в свойствах зоны (плохой вариант, поскольку влияет на всю зону);
установка индивидуального времени кэширования на отдельных записях (хороший вариант).
Для настройки индивидуального времени кэширования в консоли DNS Manager требуется сначала включить режим View –> Advanced. Затем последовательно открываем свойства записей (в нашем примере это три записи www) и ставим время кэширования, равное нулю.
Что такое DNS Round robin и как он работает-03
Проверка работы дает в конце концов желаемый результат!
C:\>ping www.gorbunov.pro –n 1
Pinging www.gorbunov.pro [20.0.0.1] with 32 bytes of data:
Request timed out.
Ping statistics for 20.0.0.1:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
C:\>ping www.gorbunov.pro –n 1
Pinging www.gorbunov.pro [30.0.0.1] with 32 bytes of data:
Request timed out.
Ping statistics for 30.0.0.1:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
C:\>ping www.gorbunov.pro –n 1
Pinging www.gorbunov.pro [40.0.0.1] with 32 bytes of data:
Request timed out.
Ping statistics for 40.0.0.1:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
Файл зоны на сервере DNS при этом будет выглядеть так:
;
; Database file gorbunov.pro.dns for gorbunov.pro zone.
; Zone version: 7
;
@ IN SOA dc01.contoso.com. hostmaster.contoso.com. (
7 ; serial number
900 ; refresh
600 ; retry
86400 ; expire
3600 ) ; default TTL
www 0 A 20.0.0.1
0 A 30.0.0.1
0 A 40.0.0.1
Добавления нуля в записи типа A можно сделать и вручную непосредственно в файле зоны.
В настройках сервера DNS по умолчанию включена и опция Enable netmask ordering. Смысл опции заключаются в том, что при наличии нескольких IP адресов для одного и того же имени хоста сервер DNS анализирует из какой сети пришел запрос от клиента. Если IP сеть клиента совпадает с номером сети одного из IP адресов хоста, то такой IP всегда возвращается первым. Проще говоря, если в нашем примере клиент с адресом 30.67.98.123 будет запрашивать имя www.gorbunov.pro, то ему всегда первым в списке будет возвращаться адрес 30.0.0.1. В серверах Windows опция Enable netmask ordering перебивает опцию Enable round robin. Т.е. клиентам DNS первым всегда возвращается адрес ближайшего хоста, даже несмотря на правильно настроенную функцию DNS Round robin.
Технология DNS Round robin часто применяется для динамической балансировки нагрузки между зеркальными хостами. Она значительно проще в реализации, чем вариант настройки для тех же целей кластера NLB. При настройке DNS Round robin на серверах Windows не забывайте, что настройки по умолчанию для сервера DNS не позволяют в полной мере реализовать балансировку запросов и требуется ручная конфигурация сервера.
Источник
Linux Blog
HowTO- Round Robin DNS
In this case we will take an example of a webservers
To use round robin, each web server must have its own public IP address. A common scenario is to use network address translation and port forwarding at the firewall to assign each web server a public IP address while internally using a private address.
This example from the DNS zone definition for foo.com assigns the same name to each of the three web servers, but uses different IP addresses for each:
;
; Domain database for foo.com
;
foo.com. IN SOA ns1.foo.com. hostmaster.foo.com. (
2006032801 ; serial
10800 ; refresh
3600 ; retry
86400 ; expire
86400 ; default_ttl
)
;
; Name servers
;
foo.com. IN NS ns1.foo.com.
foo.com. IN NS ns2.foo.com.
;
; Web servers
; (private IPs shown, but public IPs are required)
;
www IN A 10.1.1.11
www IN A 10.1.1.12
www IN A 10.1.1.13
When DNS gets a request to resolve the name www.foo.com, it will return one IP address, then a different address for the next request and so on. Theoretically, each web server will get one third of the web traffic. Due to DNS caching and because some requests may use more resources that others, the load will not be shared equally. However, over time it will come close.
This is a very good example of Load balancing using DNS server (Round Robin)
2 comments:
Found this howto which I think will be useful for someone.
Источник
How do I setup round robin DNS?
Round robin DNS is a technique in which load balancing is performed by a DNS server instead of a strictly dedicated machine. A DNS record has more than one value IP address.
When a request is made to the DNS server which serves this record, the answer it gives alternates for each request. For instance, if you had a three webserver that you wished to distribute requests between, you could setup your DNS zone as follows:
Open your zone file using vi text editor and add/modify www entry as follows:
# vi zone.cyberciti.biz
Append/modfiy www entry:
Save and restart BIND9. If you run nslookup for cyberciti.biz:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
One more time:
# nslookup cyberciti.biz
Output:
When a query is made to the DNS server it will first give the IP of 68.142.234.44 for the www host. The next time a request is made for the IP of www, it will serve 68.142.234.45 and so on.
The order in which IP addresses from the list are returned is the basis of the round robin name. While this is a form of load balancing, it should be noted that if one of the hosts becomes unavailable, the DNS server does not know this, and will still continue to give out the IP of the downed server.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Round robin dns linux
The functionality is enormously useful if you have a number of equivalent network resources, such as mirrored FTP servers, web servers, or terminal servers, and you’d like to spread the load among them. You establish one domain name that refers to the group of resources and configure clients to access that domain name, and the name server distributes requests among the IP addresses you list.
BIND 4.9 and later versions do away with the shuffle address record as a separate record type, subject to special handling. Instead, a modern name server rotates addresses for any domain name that has more than one A record. (In fact, the name server will rotate any type of record as long as a given domain name has more than one of them.[75] ) So the records:
Note that this is really load distribution, not load balancing, since the name server gives out the addresses in a completely deterministic way without regard to the actual load or capacity of the servers servicing the requests. In our example, the server at address 192.168.1.3 could be a 486DX33 running Linux and the other two servers HP9000 Superdomes, and the Linux box would still get a third of the queries. Listing a higher-capacity server’s address multiple times won’t help because BIND eliminates duplicate records.
10.7.1. Multiple CNAMEs
BIND 8 name servers, on the other hand, are more vigilant and catch this error. You can, however, explicitly configure them to allow multiple CNAME records for a single domain name with:
10.7.2. The rrset-order Substatement
BIND 8.2 and later name servers — but not BIND 9 name servers, as of 9.1.0 — allow you to turn off round robin for certain domain names and types of records. For example, if we wanted to ensure that the address records for www.movie.edu were always returned in the same order, we could use this rrset-order substatement:
The class, type, and name settings determine which records the specified order applies to. The class defaults to IN, type to ANY, and name to * — in other words, any records. So the statement:
rrset-order supports three (count ’em, three!) different orders:
fixed Always return matching records in the same order
random Return matching records in random order
cyclic Return matching records in cyclic (round robin) order
The default behavior is:
10.6. Views | 10.8. Name Server Address Sorting |
Copyright © 2002 O’Reilly & Associates. All rights reserved.
Источник