Is it important to use localhost/127.0.0.1 rather than machine’s own IP address

amazon ec2localhostloopback

I'm on Amazon AWS EC2 running Amazon Linux, though that may not be significant to the answer.

Say I have three hosts, H1, H2, H3, with private IP addresses of 10.0.0.1, 10.0.0.2, and 10.0.0.3. This could be represented in a /etc/hosts file with these lines:

127.0.0.1   localhost localhost.localdomain
10.0.0.1    H1
10.0.0.2    H2
10.0.0.3    H3

In php code I do things like run curl to access stuff on a particular host, based on implicit knowledge of what that hosts offers. I'd rather not concern myself with whether the particular host I'm accessing is the host running the code itself, just access H1, H2, or H3. I could use a different /etc/hosts file on each host, changing the line with its private IP address to use the address 127.0.0.1. But is that actually significant? If I use identical /etc/hosts files on all the machines, am I sacrificing any performance or functionality?

Does network access made to a machine's own private IP address actually cause real "external" traffic or is it detected and uses the loopback connector like 127.0.0.1 does anyway? Does the process receiving the request see the originating address as the machine's own private IP address, or does it see 127.0.0.1 anyway?

Best Answer

Using an identical hosts file is fine and will have no performance impact, the traffic stays local if you connect to H1 from H1. However, if you connect to localhost/127.0.0.1, the source IP will be 127.0.0.1 as well, but if you connect to H1, the source IP will be 10.0.0.1 (e.g. in the Apache log).

One difference: Some applications, notably MySQL/MariaDB, switch to using Unix Domain sockets for traffic if you connect to localhost, but use the IP stack when using 127.0.0.1 or the actual IP address or hostname of the machine. This is said to have a slight performance benefit, though I've never actually benchmarked this.