godnsresolvemusl

golang's handling of localhost


I have an alpine linux system which uses the musl libc and therefore has no /etc/nsswitch.conf.

According to tcpdump on this system, net.LookupIP("localhost") actually does a query for localhost.a.b.c, where a.b.c is taken from domain a.b.c in /etc/resolv.conf. But if I add an /etc/nsswitch.conf with hosts: files dns, it correctly looks up localhost from /etc/hosts.

As far as I can tell, no libc implementation tries to add a domain to localhost when looking it up in DNS. So (a) is there some good reason it's done this way or is it a bug? and (b) is there a way to work around it without adding an nsswitch.conf and while still using just the name localhost?

Edit More details:

ldd ./dnstest
    /lib/ld-musl-armhf.so.1 (0x76f2c000)
    libc.so => /lib/ld-musl-armhf.so.1 (0x76f2c000)

So yes, there is a dependency on libc.so. I have tried this with CGO_ENABLED=1 and with CGO_ENABLED=0 in the build commandline, too.


Solution

  • So currently, it still needs RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf as workaround to use alpine image as base image to run golang binary.