Linux local dns cache

How to Setup a local DNS Caching Server on Linux?

Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.

DNS lookups are not normally something that you need to worry about. Sometimes you should!

If your home or office’s ISP has slow nameservers or your server is performing lots of lookups, then you need a local caching DNS server.

How will a caching DNS server help me?

A caching DNS server works by performing all the DNS queries that your system makes and then saving, or caching, the results in memory. Once that the results are cached in memory any time that you make a duplicate request for a domain, the result will get served almost instantaneously from memory.

This may not seem too important, but if your ISP’s DNS servers are taking their time to respond, it will slow down your internet browsing considerably. For example, the home page for the US news channel MSNBC needs to contact over 100 unique domains names to load correctly. If your ISP’s name servers are taking even a 10th of a second longer than normal to respond, that means that the page will take 10 seconds longer to finish loading.

A local caching DNS server will not only help in your home or office it will also help on your server. If you have an application that makes lots of DNS lookups, for example, a busy email server running anti-spam software it will receive a speed boost from a local caching DNS server.

Finally, systemd-resolved supports the very latest, secure DNS standards DNSSEC and DNSoverTLS or DoT. These help keep you secure and retain your privacy online.

Which local caching DNS will we use?

The local caching DNS server that we will enable and configure in this guide is systemd-resolved. This tool is a part of the systemd suite of system management tools. If your system is using systemd, and almost all of the major Linux distributions are, then you will already have systemd-resolved installed but not running. Most distributions do not use systemd-resolved even though it is present.

systemd-resolved works by running a small local caching DNS server which we will configure to start on boot. We will then re-configure the rest of the system to direct their DNS queries to the local caching systemd-resolved DNS.

How to check if you are already using systemd-resolved?

Some Linux distributions are already using systemd-resolved by default such as Ubuntu 19.04.

If you are already running systemd-resolved then you do not need to enable it or configure your system to use it. You may, however, need to ensure that network management tools like NetworkManager are configured correctly as they can ignore system network configuration.

Before proceeding to the next section run the following command to check if you are already running systemd-resolved:

If you get the message:

You are not running systemd-resolved and should move on to the next section. If, instead, you see output that begins with something like the following:

Then you are already running systemd-resolved and do not need to enable it.

Enabling and configuring systemd-resolved

We do not need to install systemd-resolved as already a part of systemd. All that we need to do is to start it to get the DNS caching server running and then enable it to start it on boot.

Run the following command from a shell prompt as a sudo enabled a non-root user to start systemd-resolved:

Читайте также:  Windows 10 где включить микрофон

Next, run the following command to start systemd-resolved on system boot-up:

The last item of configuration left is to set the DNS servers that systemd-resolved will query to resolved domains. There are many options here, but either of the following pairs is free, fast, and they both support DNSSEC and DoT:

Open the main systemd-resolved configuration file with your favorite text editor, here I have used nano:

Edit the line begins

So that a pair of the IP addresses are listed. Here, the Cloudflare DNS servers are shown:

Save and exit the text editor. We now need to restart systemd-resolved so that it starts to use the nameservers:

systemd-resolved is now running and ready to start speeding-up and securing DNS queries as soon as we configure the system to begin using it.

Configuring the system to use systemd-resolved

Your system can be configured in several ways to use systemd-resolved, but we will look at two configurations that cover most use cases. The first is the recommended configuration, and the second is the compatibility configuration. The difference between the two is how the /etc/resolv.conf file is managed.

The /etc/resolv.conf file holds the IP addresses of the nameservers that programs on the system should query. Programs that need to make DNS queries will consult this file to find out what servers they should contact to make those queries.

The two modes of systemd-resolved center around how the contents of this file are managed. In the recommended mode, /etc/resolv.conf is made a symlink to /run/systemd/resolve/stub-resolv.conf. This file is managed by systemd-resolved and therefore systemd-resolved manages the DNS configuration information for all other programs on the system.

This can cause problems when other programs try to manage the contents of /etc/resolv.conf. Compatibility mode leaves /etc/resolv.conf in place allowing other programs to manage it while systemd-resolved uses that DNS information. In this mode, the other programs managing /etc/resolv.conf must be configured to set 127.0.0.53 as the system nameserver in /etc/resolv.conf.

When we configure this mode systemd-resolved will manage /etc/resolv.conf by making it a symlink to /run/systemd/resolve/stub-resolv.conf. We will need to do this by hand as it is not configured automatically.

First, delete or rename the existing /etc/resolv.conf file. Renaming is a better option to deleting it as it will have the same effect but you can always refer to the original if you need the information it contains. Here, we rename /etc/resolv.conf using the mv command:

Next, create the symlink:

Finally, restart systemd-resolved:

Configuring the compatibility mode

In this mode, you need to ensure that the local nameserver that systemd-resolved has started is queried by system services. Open /etc/resolv.conf in a text editor, here the nano editor is used:

Delete any lines you encounter that begin with “nameserver” and add this line:

This edit may get changed by any other program that is managing /etc/resolv.conf. If this is the case then you will need to configure those programs to use this nameserver to make the edit permanent.

Debugging systemd-resolved

Discovering exactly how your system is making DNS queries after you have made these changes can be difficult. The most effective way method of observing what is happening is to put systemd-resolved into debugging mode and watch the log file.

systemd-resolved is a systemd service, which means that it can be easily put into debugging mode by creating a drop-in service file that contains the debug setting. The following command will create the correct file in the correct location:

Paste the following lines into the editor then save and exit:

The systemd-resolved service will be automatically reloaded on a successful save and exit.

Open a second terminal to the same server and follow the journald log for the systemd-resolved service:

A line that begins “Using DNS server” e.g.:

Tells you exactly which DNS server is being used for DNS queries. In this case, the Cloudflare DNS server at 1.1.1.1 was queried.

Lines that being “Cache miss” indicate that the domain name has not been cached. E.g.:

Lines that begin “Positive cache hit” e.g.:

Indicate that systemd-resolved has queried this domain before and the answer was served from the cache in the local memory.

Читайте также:  Графические менеджеры пакетов linux

You should disable debugging mode when you have finished working systemd-resolved as it will create a very large log file on a busy system. You can disable the debug logging by running:

and deleting the two lines, you added then saving and exiting the editor.

Using secure DNS queries

systemd-resolved is one of the few, currently available DNS servers that support both DNSSEC and DNSoverTLS. Both of these help to ensure that you are receiving genuine DNS information (DNSSEC) and that no one can snoop on your DNS traffic as it passes over the internet. (DoT).

These options are easily enabled by opening systemd-resolved’s main configuration file with a text editor:

And editing the file so that the following two lines are set:

Save and exit the editor then reload systemd-resolved:

As long as the DNS server you have set support DNSSEC and DoT your DNS queries will be protected. The Google and Cloudflare public DNS servers both support these protocols.

Conclusion

Your system is now configured to speedily and efficiently make DNS queries even when your ISP’s DNS server are not responding as quickly as they should. Furthermore, your digital life is more secure as you are using the latest, secure DNS protocols to protect your DNS queries.

If you are Linux enthusiast and looking to learn more, then check out this fantastic online course.

Источник

ИТ База знаний

Курс по Asterisk

Полезно

— Узнать IP — адрес компьютера в интернете

— Онлайн генератор устойчивых паролей

— Онлайн калькулятор подсетей

— Калькулятор инсталляции IP — АТС Asterisk

— Руководство администратора FreePBX на русском языке

— Руководство администратора Cisco UCM/CME на русском языке

— Руководство администратора по Linux/Unix

Серверные решения

Телефония

FreePBX и Asterisk

Настройка программных телефонов

Корпоративные сети

Протоколы и стандарты

Установка локального сервера кеширования DNS на Linux

Время поднимать кэширующий сервер

На самом деле поиск DNS это не то, что требует частого внимания. Но иногда приходится заботиться об этом. Например, если у вашего провайдера слабые сервера или же в вашей сети часто происходят DNS обращения, то нужно настроить локальный кэширующий DNS сервер.

Мини — курс по виртуализации

Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена

Как кэширующий DNS-сервер может пригодиться?

Кэширующий DNS-сервер занимается обработкой DNS запросов, которые выполняет ваша система, затем сохраняет результаты в памяти или кэширует их. В следующий раз, когда система посылает DNS запрос для того же адреса, то локальный сервер почти мгновенно выдает результат.

Эта идея может показаться бесполезной. Подумаешь, какие-то там секунды. Но если DNS сервера провайдера тратят много времени на разрешение имени, то в результате падает скорость Интернет серфинга. Например, домашняя страница новостного канала MSNBC для корректной работы обращается более чем к 100 уникальным доменам. Даже если на запрос тратится одна десятая секунды, в итоге получается 10 секунд ожидания, что по нынешним меркам слишком много.

Локальный кэширующий DNS увеличивает скорость не только дома или в офисе, он также помогает работе серверов. Например, у вас есть почтовый сервер с анти-спам фильтром, который выполняет очень много DNS запросов. Локальный кэш намного увеличить скорость его работы.

И наконец, system-resolved поддерживает новейшие стандарты вроде DNSSEC и DNSoverTLS или DoT. Эти технологии увеличивают безопасность при работе в Интренет.

Какой локальный кэширующий сервер выбрать?

В этом руководстве будет использован сервер systemd-resolved . Эта утилита является частью набора управления системой systemd . Если в вашей системе используется systemd , а большинство дистрибутивов Linux используют это, то в системе уже установлен systemd-resolved , но не запущен. Большинство систем не используют эту утилиту.

systemd-resolved запускает небольшой локальный кэширующий DNS-сервер, который мы настроим на запуск при загрузке системы. Затем мы изменим конфигурацию всей системы так, чтобы DNS запросы шли на локальный сервер.

Как проверить используется ли systemd-resolved?

В некоторых дистрибутивах, например Ubuntu 19.04, по умолчанию используется systemd-resolved .

Если у вас уже запущен systemd-resolved , тогда не нужно что-то настраивать в системе. Но нужно проверить на корректность утилит управления сетевыми настройками, такие как NetworkManager, так как они могут игнорировать системные настройки сети.

Перед тем как перейти к следующему разделу проверьте запущен ли в вашей системе systemd-resolved :

Читайте также:  Rosa linux ��������� ����� ���������

Если в ответ получите сообщение ниже, значит в системе не настроен systemd-resolved :

И наоборот, если на выходе видите что-то подобное, то systemd-resolved уже работает:

Включение и настройка systemd-resolved

Отдельно устанавливать systemd-resolved не нужно, так как этот сервис является частью systemd . Всё что нужно сделать это запустить его и добавить в автозагрузку. Для включения данной службы введите команду ниже:

Далее нужно ввести следующую команду, чтобы добавить службу в автозапуск.

И наконец нужно прописать DNS сервера, куда будет обращаться локальный сервер для разрешения имен. Есть много разных сервисов, но приведённые ниже самые быстрые, бесплатные и оба поддерживают DNSSEC и DoT:

Google Public DNS

Cloudflare Public DNS

Для этого откройте конфигурационный файл systemd-resolved любым текстовым редактором:

Отредактируйте строку, которая начинается на:

И пропишите одну из вышеуказанных пар. Мы используем Cloudflare Public DNS:

Сохраните изменения и перезапустите службу systemd-resolved :

Итак, systemd-resolved уже запущен и готов для выполнения быстрых и безопасных DNS запросов, как только мы настроим систему соответствующим образом.

Настройка системы для использования systemd-resolved

Есть несколько путей настройки системы на использование локального DNS сервера. Мы рассмотрим два наиболее используемых метода. Первый – рекомендуемый метод, второй конфигурация в режиме совместимости. Разница в том, как будет обрабатываться файл /etc/resolv.conf .

В файле /etc/resolv.conf содержатся IP адреса серверов разрешения имен, которые используются программами. Программы при необходимости разрешения доменного имени обращаются к этому файлу в поисках адресов серверов разрешения имен.

Итак, первый метод конфигурации заключается в создании символьной ссылки на /run/systemd/resolve/stub-resolv.conf . В этом случае файл /etc/resolv.conf управляется службой systemd-resolved .

Это может вызвать проблемы в том случае, если другие программы пытаются управлять файлом /etc/resolv.conf . Режим совместимости оставляет /etc/resolv.conf не тронутым, позволяя программам управлять им. В этом режиме, в настройках программ, управляющих файлом /etc/resolv.conf в качестве системного сервера разрешения имен должен быть указан IP 127.0.0.53 .

Конфигурация в рекомендуемом режиме

При этом режиме конфигурация проводится вручную. Сначала нужно удалить или переименоваться оригинальный файл /etc/resolv.conf . Лучше переименовать, чтобы при необходимости можно было использовать информацию в нем

Затем создаем символьную ссылку:

И наконец перезапускаем службу systemd-resolved :

Настройка в режиме совместимости

В режиме совместимости, нужно убедиться, что локальный сервер разрешения имен system-resolved запущен и используется системными службами. Откройте файл /etc/resolv.conf любым редактором:

Удалите все строки, которые содержать ключевое слово nameserver и добавьте одну единственную строку:

Этот файл мажет быть изменён любой программой. Чтобы предотвратить это нужно настроить программы так, чтобы в качестве DNS они использовали адрес 127.0.0.53 .

Отладка systemd-resolved

Посмотреть, как система выполняет DNS запросы после внесённых изменений сложно. Самый эффективный метод – это включить режим отладки для службы systemd-resolved , а затем просмотреть файл логов.

systemd-resolved можно перевести в режим отладки созданием специального служебного файла, в котором содержатся настройки отладки. Делается это следующей командой:

Вставьте в файл следующие строки:

После этого служба systemd-resolved автоматический перезапуститься. Откройте второй терминал и просмотрите логи в journald :

Строка, которая содержит слова “Using DNS server” показывает, какой DNS сервер используется для разрешения имён. В нашем случае это DNS сервера Cloudflare

Слова “Cache miss” в начале строки означает, что для данного домена нет закэшированной информации:

И наконец слова “Positive cache” в начале строки означает, что systemd-resolved уже запрашивал информацию об этом домене и теперь ответы возвращает из кэша:

Не забудьте отключить режим отладки, так как в это время создается большой файл логов. Сделать это можно командой:

а затем удалить добавленные выше две строки.

Использование защищенных DNS запросов

systemd-resolved один из немногих DNS серверов, которые поддерживает DNSSEC и DNSoverTLS. Эта два механизма позволяют убедиться, что полученная DNS информация подлинная (DNSSEC) и он не был изменён по пути (DoT).

Эти функции легко включаются редактированием основного конфигурационного файла system-resolved :

Измените файл следующим образом:

Сохраните изменения и перезапустите службу systemd-resolved .

Пока прописанные DNS сервера поддерживают эти две функции все DNS запросы будут защищены. DNS сервера Google и CloudFlare поддерживают эти механизмы защиты.

Заключение

Теперь ваша система будет выполнять DNS запросы быстро и эффективно даже если провайдер не работает достаточно быстро. Кроме этого, ваша цифровая жизнь лучше защищена новейшими механизмами защиты DNS запросов.

Онлайн курс по Linux

Мы собрали концентрат самых востребованных знаний, которые позволят тебе начать карьеру администратора Linux, расширить текущие знания и сделать уверенный шаг к DevOps

Источник

Оцените статью