/etc/hosts vs. /etc/resolv.conf

When an application performs DNS lookup as part of its operations on Linux, it can leverage both /etc/hosts and /etc/resolv.conf configuration files to resolve DNS names. How these configuration files are used for DNS lookup can vary among different applications, complicating system administration. But Linux libc library and the GNU C Library (glibc) provides a clean solution to this problem, by defining DNS lookup orders with Name Service Switch (NSS). NSS defines a set of databases and their lookup order in NSS configuration file (/etc/nsswitch.conf in Linux). Applications built with those libraries will then perform DNS lookups in a consistent manner.

In /etc/nsswitch.conf, the database for DNS lookup is called "hosts". For example:

$ cat /etc/nsswitch.conf | grep "hosts"
hosts: files dns

The above means that DNS lookup refers to /etc/hosts first, and then DNS servers specified in /etc/resolv.conf

gethostbyname() in glibc will follow the DNS lookup order specified in /etc/nsswitch.conf. So do other programs like wget and curl.

Note that DNS lookup tools such as nslookup/dig which are made to query DNS servers, will ignore /etc/nsswitch.conf, and always refer to DNS servers in /etc/resolv.conf


Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

Leave a comment

Your email address will not be published. Required fields are marked *

Current ye@r *