Reason is most probably the systemd-resolvd.
Checking configs:
root@sf:~# grep localhost /etc/hosts
127.0.0.1 localhost
::1 ip6-localhost ip6-loopback
root@sf:~# grep nameserver /etc/resolv.conf
nameserver 127.0.0.53
127.0.0.53 is the systemd resolver.
Now do pings:
root@sf:~# ping -c 1 foo.localhost
PING foo.localhost(ip6-localhost (::1)) 56 data bytes
64 bytes from ip6-localhost (::1): icmp_seq=1 ttl=64 time=0.035 ms
--- foo.localhost ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.035/0.035/0.035/0.000 ms
root@sf:~# ping -c 1 serverfault.com
PING serverfault.com (151.101.129.69) 56(84) bytes of data.
64 bytes from 151.101.129.69 (151.101.129.69): icmp_seq=1 ttl=59 time=16.8 ms
--- serverfault.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 16.802/16.802/16.802/0.000 ms
Yes, it works exactly like your ping.
Now switch from systemd resolver to my LAN's dns cache:
root@sf:~# sed -i '/nameserver/s,.*,nameserver 192.168.101.1,' /etc/resolv.conf
root@sf:~# grep nameserver /etc/resolv.conf
nameserver 192.168.101.1
Doing pings again:
root@sf:~# ping -c 1 foo.localhost
ping: foo.localhost: Name or service not known
root@sf:~# ping -c 1 serverfault.com
PING serverfault.com (151.101.129.69) 56(84) bytes of data.
64 bytes from 151.101.129.69 (151.101.129.69): icmp_seq=1 ttl=59 time=16.4 ms
--- serverfault.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 16.426/16.426/16.426/0.000 ms
Voila!