Linux – Should /etc/hosts contain an entry like ‘127.0.0.1 localhost thehost.example.org thehost’

linuxlinux-networking

When looking at a variety of Linux and FreeBSD systems, I've noticed that on some systems /etc/hosts contains an entry for the public hostname of the host, but not on other systemst.

What is the best practice here? Should my /etc/hosts file contain an entry for the hosts FQDN (e.g. myhost.example.org) and for the short hostname (e.g. myhost)? Should the record for the FQDN point to the localhost or should it point to the external IP of the box?

For example, the default configuration on many RHEL/EL boxes doesn't put the public hostname into /etc/hosts:

myhost # cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
myhost #

The other variant is that the host's short hostname and FQDN also point to 127.0.0.1. I've been told that this is an older practice which is frowned upon these days, but plenty of admins still do this.

myhost # cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4 myhost myhost.example.org
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
myhost #    

The third variant is that the hosts's FQDN and short hostname are given the external IP address of the host. This third varient seems optimal to me because it reduces lookups against the DNS servers.

myhost # cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
74.125.239.xxx myhost myhost.example.org
myhost #  

What is the best practice here?

Best Answer

Are you willing to accept working DNS a point of failure in your environment or not. Some services/applications will fail in certain configurations if a system cannot resolve the local machine's name.

If you have an absolutely critical service that must be running in all situations, it isn't unusual to add a an entry in the hosts file so that service can continue to operate in the situation where DNS resolution fails.

If you can accept your DNS as a point of failure, or if your services don't fail in the case of broken resolution, configuration entries in the hosts file can be avoided.

I strongly suggest you make your DNS servers as rock solid as possible, and if you must configure your hosts file, use a configuration management system to do it. You really should avoid manually avoid touch a hosts file.