This is really an OS resolver question at its heart, but you did not specify the operating system. Since dig
is mentioned, I'm going to assume that we're working with some flavor of UNIX here.
UNIX based operating systems do not implement a DNS cache within the kernel itself. There are a few topics that need to be summarized before we get into how it's actually implemented.
NSS
Calls to the resolver library typically implement their lookups using Name Service Switch (NSS), a modular system for specifying data sources to use and the order in which they are looked up. You can find a list of these module stacks in /etc/nsswitch.conf
. For reference, the one we're concerned with here is hosts
.
It is not recommended to play with the hosts
entry in /etc/nsswitch.conf
unless you really know what you're doing. Reordering these modules can result in funky things like DNS consulted before the /etc/hosts
file!
nscd
Prior to consulting the module stack, NSS checks for the presence of a running nscd
socket and attempts to query it. If nscd
is configured to maintain a cache for the NSS database in question, it's possible that an entry cached by nscd
will be returned without the NSS modules being consulted. Most Linux distros that I know of do not enable caching of the hosts
database by default, and /etc/nscd.conf
must be customized.
That said, it should be noted that many administrators consider the "stock" nscd
daemon to be unreliable, at least under Linux. There is at least one alternate implementation out there. Your mileage may vary.
Putting it all together
Knowing the above, the lookup order for the hosts database works in this order:
nscd
(if running, its socket is present, and caching of hosts is enabled)
- NSS modules, in the order listed in
/etc/nsswitch.conf
- If not found in a NSS module, it doesn't exist.
This brings us to where dig
falls into this equation. You can pretty much refer to HBrujin's entire answer (dig
doesn't use NSS, only talks over TCP/IP), but the catch is that there is no cache for NSS at all unless 1) nscd
is running, and 2) it is configured to cache the hosts
database.
tl;dr
The complexity of getting DNS caching to play nicely within NSS is usually why most admins go with the "simpler" solution of running their own recursive DNS server. You don't need to know a darn thing about NSS. Just point /etc/resolv.conf
at your shiny new DNS cache and let it hide the evils of NSS from you. (at least until you need to learn how LDAP integration works)