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

Last updated on July 24, 2020 by Dan Nanni

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 follows 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 or dig which are made to query DNS servers, will ignore /etc/nsswitch.conf, and always refer to DNS servers in /etc/resolv.conf.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean