Sunday, April 25, 2021

Do not trust "localhost": It is just a name

Like any other domain name or host name, "localhost" is yet another name. It needs to be resolved first when it is used. Usually, the entries needed to resolve it are already in the `hosts` file when the OS is installed.

$ ping localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.140 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.147 ms
64 bytes from localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.148 ms
64 bytes from localhost (127.0.0.1): icmp_seq=4 ttl=64 time=0.126 ms
^C
--- localhost ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3059ms
rtt min/avg/max/mdev = 0.126/0.140/0.148/0.008 ms

$ ping6 localhost
PING localhost(ip6-localhost (::1)) 56 data bytes
64 bytes from ip6-localhost (::1): icmp_seq=1 ttl=64 time=0.099 ms
64 bytes from ip6-localhost (::1): icmp_seq=2 ttl=64 time=0.175 ms
64 bytes from ip6-localhost (::1): icmp_seq=3 ttl=64 time=0.221 ms
64 bytes from ip6-localhost (::1): icmp_seq=4 ttl=64 time=0.161 ms
^C
--- localhost ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3074ms
rtt min/avg/max/mdev = 0.099/0.164/0.221/0.043 ms

The pitfall here is, if you simply use "localhost" in your application, it could behave differently when deployed in different environments. In extreme cases, I have seen "localhost" get resolved to its IPv4 and IPv6 entries (i.e., "127.0.0.1" and "::1") randomly within a single integration test run. Think about it! What if the service, that your application is trying to connect to, ONLY listens to its ports on the IPv4 address? In such a case, a connection request sent to "::1" will be refused.

Tips

  1. If you see "connection refused", always check if the ports are open on both "127.0.0.1" and "::1". Do not preclude this possibility even if the error is intermittent.
  2. Docker containers' forwarded ports might be open on "127.0.0.1" only on the host.
  3. If you cannot solve the resolving issue in the environment, there might be workarounds where you can configure your application to prefer the IPv4 stack when resolving host names.

1 comment:

  1. When you send money, you are 1xbet be} giving your personal monetary and banking data to unknown persons that aren't licensed or regulated in handling it. Play at one of the best sportsbooks and casinos for on-line gambling today! Browse our shortlist to find out|to search out} safe websites that offer actual money gambling, huge bonuses, hundreds of games, sports activities betting, and extra.

    ReplyDelete