- How to setup DNS manually on Linux?
- 2 Answers 2
- DNS Config Under Linux
- Getting Back The Control Of DNS
- 1. Resolvconf:
- 2. Dnsmasq Service:
- 3. Network Manager:
- 4. Network Interfaces:
- 5. DHCP Client:
- 6. Rdnssd Service:
- 7. Resolved Service:
- 8. Netconfig:
- Setting The DNS Server
- How to Setup Local DNS Using /etc/hosts File in Linux
- Understanding Name Service Switch in Linux
- Configure DNS Locally Using /etc/hosts File in Linux
- Related Posts
- 3 thoughts on “How to Setup Local DNS Using /etc/hosts File in Linux”
- Как посмотреть DNS в Linux
- Как посмотреть DNS в Linux
How to setup DNS manually on Linux?
In Linux /etc/resolv.conf get often overwritten when we setup the DNS, because of the multitude of programs managing the DNS servers. How to properly setup the DNS ?
2 Answers 2
DNS Config Under Linux
DNS usage on linux is done over a set of routines in the C library that provide access to the Internet Domain Name System (DNS). The resolver configuration file ( resolv.conf ) contains information that is read by the resolver routines the first time they are invoked by a process. In short each process requesting DNS will read /etc/resolv.conf over library. The NSS is layered on top of this, and is configured by /etc/nsswitch.conf .
Linux DNS config are located in the file /etc/resolv.conf BUT there are a number of programs/services that wants to automatically manage and handle the DNS configuration file at /etc/resolv.conf . In some situations you may want to manage this file yourself. Each program/service managing DNS have its own configuration files like /etc/dnsmasq.conf (for dnsmasq service) and append the DNS config at connection change and/or on other events. a quick solution is to lock the DNS config file with chattr +i /etc/resolv.conf but this is not recommended in certain case, a better solution is to setup correctly all the program/services using the DNS like (dnsmasq/network-manager/resolvconf/etc.)
Getting Back The Control Of DNS
Here is an exhaustive list of setups to get back the control of resolv.conf and avoid having it overwritten (how to disable/setup DNS from other location other than resolv.conf) note that resolvconf is an independent program from resolv.conf, also depending on your system/config you may not have one or many of the programs listed here.
1. Resolvconf:
cat /etc/resolvconf/resolv.conf.d/head nameserver 8.8.4.4 cat /etc/resolvconf/resolv.conf.d/base nameserver 8.8.4.4
systemctl disable --now resolvconf.service
2. Dnsmasq Service:
cat /etc/dnsmasq.conf server=1.1.1.1 server=8.8.4.4
sudo systemctl restart dnsmasq.service
3. Network Manager:
$ cat /etc/NetworkManager/conf.d/no-dns.conf [main] dns=none
$ cat /etc/NetworkManager/conf.d/dns.conf [main] dns=default [global-dns] searches=example.com [global-dns-domain-*]
$ cat /usr/lib/NetworkManager/conf.d/resolved.conf [main] dns=systemd-resolved
$ cat /usr/lib/NetworkManager/conf.d/resolvconf.conf [main] rc-manager=resolvconf
systemctl restart NetworkManager.service
4. Network Interfaces:
$ cat /etc/network/interfaces #nameservers # or dns-search like so # dns-search x.y dns-nameservers 4.4.4.4 8.8.8.8
5. DHCP Client:
$ cat /etc/dhcp3/dhclient.conf supersede domain-name-servers ,;
6. Rdnssd Service:
systemctl disable --now rdnssd.service
7. Resolved Service:
systemctl disable --now systemd-resolved.service
8. Netconfig:
/etc/sysconfig/network/config
cat /etc/sysconfig/network/config NETCONFIG_DNS_POLICY=""
Setting The DNS Server
Example of a /etc/resolv.conf configuration
#Cloudflare nameserver 1.0.0.1 #Google #nameserver 8.8.8.8 #nameserver 8.8.4.4 #Cloudflare #nameserver 1.1.1.1 #Classic Config #nameserver 192.168.1.1 #search lan
How to Setup Local DNS Using /etc/hosts File in Linux
DNS (Domain Name System or Service) is a hierarchical decentralized naming system/service that translates domain names into IP addresses on the Internet or a private network and a server that provides such a service is called a DNS server.
This article explains, how to setup a local DNS using the hosts file (/etc/hosts) in Linux systems for local domain resolution or testing the website before taking live.
For example, you may want to test a website locally with a custom domain name before going live publicly by modifying the /etc/hosts file on your local system to point the domain name to the IP address of the local DNS server you configured.
The /etc/hosts is an operating system file that translate hostnames or domain names to IP addresses. This is useful for testing websites changes or the SSL setup before taking a website publicly live.
Attention: This method will only work if the hosts have a static IP address. Therefore ensure that you have set static IP addresses for your Linux hosts or nodes running other operating systems.
For the purpose of this article, we will be using the following domain, hostnames and IP addresses (use values that apply to your local setting).
Domain: tecmint.lan Host 1: ubuntu.tecmint.lan 192.168.56.1 Host 2: centos.tecmint.lan 192.168.56.10
Understanding Name Service Switch in Linux
Before moving any further, you should understand a few things about another important file that is /etc/nsswitch.conf. It provides Name Service Switch functionality which controls the order in which services are queried for name service lookups.
The configuration is based on order; if files is before dns it means the system will query the /etc/hosts file before checking DNS for name service requests. But if DNS is before files then the domain lookup process will consult DNS first before any other appropriate services or files.
In this scenario, we want to query the “files” service. To check the order, type.
$ cat /etc/nsswitch.conf OR $ grep hosts /etc/nsswitch.conf
Configure DNS Locally Using /etc/hosts File in Linux
Now open the /etc/hosts file using your editor of choice as follows
Then add the lines below to the end of the file as shown in the screen shot below.
192.168.56.1 ubuntu.tecmint.lan 192.168.56.10 centos.tecmint.lan
Next, test if everything is working well as expected, using the ping command from Host 1, you can ping Host 2 using it domain name like so.
$ ping -c 4 centos.tecmint.lan OR $ ping -c 4 centos
On the Host 2, we have setup Apache HTTP server. So we can also test if the name translation service is working as follows by going to URL http://centos.tecmint.lan.
Important: To use the domain names on any host on the network, you must configure the above settings in its /etc/hosts file.
What does this mean, in the above example, we only configured the hosts file of Host 1 and we can only use the domain names on it. To use the same names on Host 2, we have to add the addresses and names to its hosts file as well.
Lastly, you should use host command or nslookup command to test if the name translation service is actually working, these commands only query DNS and overlook any configurations in /etc/hosts and /etc/nsswitch.conf files.
You may also like to read these following related articles.
That’s it! Do share any additional thoughts or questions about this topic with us, via the comment section below.
Aaron Kili is a Linux and F.O.S.S enthusiast, an upcoming Linux SysAdmin, web developer, and currently a content creator for TecMint who loves working with computers and strongly believes in sharing knowledge.
Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.
Related Posts
3 thoughts on “How to Setup Local DNS Using /etc/hosts File in Linux”
Linux does provide the bind RPM package to allow an administrative domain to configure and maintain its own DNS service, but frequently the size of the local network is only a few hosts and makes justifying the effort of maintaining a DNS service unwarranted. Reply
Please refer to https://unix.stackexchange.com/questions/421491/what-is-the-purpose-of-etc-hosts . Reply
Hello Aaron, I’m sad to say that in above article you did not describe DNS at all. You instead described how to configure local name resolution on a Linux host through /etc/hosts. In this scenario, DNS is not involved at all. Think of OS name resolution like an umbrella. In nsswitch.conf the sysadmin configures what name resolution services for this system should be. Files usually come first (means /etc/hosts), DNS is one of them – it usually follows files but there are a lot more different name resolution services and strategies available. “getent hosts ” query the OS to resolve according to configured name resolution services in that order (and usually checks /etc/hosts firsts and then maybe DNS, but always does what’s written in nsswitch.conf behind “hosts:”) “host” explicitly asks DNS service to resolve. This won’t resolve hostnames that only /etc/hosts can resolve – to demonstrate the difference. Please read the man pages of “getent” and “hosts“. I suggest completely overhaul this article or take it off-line. Greetings,
Joerg Reply
Как посмотреть DNS в Linux
Служба DNS или Domain Name System позволяет превращать легко читаемый адрес сайта в ip адрес сервера на котором расположен этот сайт. Для этого используются DNS серверы, которые содержат таблицы соответствия ip адресов их доменным именам. По умолчанию система получает адрес DNS сервера автоматически по DHCP при подключении к сети.
В этой статье мы разберемся как посмотреть какие DNS серверы используются в Linux.
Как посмотреть DNS в Linux
Если вы уже имели опыт настройки сети в Linux, то знаете, что DNS серверы, используемые для резолвинга доменных имен указаны в файле /etc/resolv.conf:
Но в современных дистрибутивах Linux с системой инициализации systemd обычно запущен локальный DNS сервер, адрес которого и прописан в этом файле, а какие сервера используются на самом деле непонятно. В таком случае можно воспользоваться утилитой systemd-resolve:
В самом низу вывода утилиты можно посмотреть DNS в Linux, которые сейчас используются. Информация выводится по каждому сетевому интерфейсу отдельно.
Также для решения подобной задачи можно использовать утилиту nmcli:
Как видите, все очень просто. А чтобы изменить DNS сервер тоже трогать /etc/resolv.conf не желательно, так как он будет автоматически обновляться после перезагрузки. Если вы используете NetworkManager, то можно настроить DNS для сетевого подключения в интерфейсе программы. Или же можно отредактировать файл /etc/systemd/resolved.conf и добавить нужные адреса в секцию Resolve:
sudo vi /etc/systemd/resolved.conf
Как видите, все очень просто. Надеюсь, эта информация была вам полезной.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.