Linux – Why does *.localhost resolve to 127.0.0.1 and ::1

arch linuxdns

I discovered by chance (trying to access a proxied service in a Docker container on a Vagrant box using servicename.docker.localhost from the host) that any hostname ending in ".localhost" resolves to 127.0.0.1 or ::1 on my machine:

$ ping -4 -c1 -n foo.localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.147 ms

--- localhost ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.147/0.147/0.147/0.000 ms
$ ping -6 -c1 -n foo.localhost
PING foo.localhost(::1) 56 data bytes
64 bytes from ::1: icmp_seq=1 ttl=64 time=0.072 ms

--- foo.localhost ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.072/0.072/0.072/0.000 ms

However, there is no DNS entry for this:

$ nslookup -type=AAAA foo.localhost
Server:     192.168.2.82
Address:    192.168.2.82#53

** server can't find foo.localhost: NXDOMAIN
$ nslookup -type=A foo.localhost
Server:     192.168.2.82
Address:    192.168.2.82#53

** server can't find foo.localhost: NXDOMAIN

/etc/hosts doesn't look particularly relevant:

127.0.0.1   my-machine-name.my-work-domain  my-machine-name localhost.localdomain   localhost
::1     localhost.localdomain   localhost

Neither does /etc/resolv.conf:

domain my-work-domain
search my-work-domain
nameserver 192.[…]
nameserver 192.[…]

Why does *.localhost magically resolve?

This is similar but possibly distinct from this question.


$ getent hosts
127.0.0.1       my-machine-name.my-work-domain my-machine-name localhost.localdomain localhost
127.0.0.1       localhost.localdomain localhost
$ getent hosts foo.localhost
::1             localhost

Best Answer

This is caused by the myhostname NSS module which defines the hostname and any name ending in .localhost as 127.0.0.1 in ipv4 and ::1 in ipv6.

https://www.freedesktop.org/software/systemd/man/nss-myhostname.html