Various software relies on an always-resolvable local hostname. When using dynamic hostnames, this is traditionally achieved by patching /etc/hosts at the same time as changing the hostname. This is problematic since it requires a writable /etc/ file system and is fragile because the file might be edited by the administrator at the same time. With nss-myhostname enabled, changing /etc/hosts is unnecessary, and on many systems, the file becomes entirely optional.
To activate the NSS modules, add "myhostname" to the line starting with "hosts:" in /etc/nsswitch.conf.
It is recommended to place "myhostname" either between "resolve" and "traditional" modules like "dns", or after them. In the first version, well-known names like "localhost" and the machine hostname are given higher priority than the external configuration. This is recommended when the external DNS servers and network are not absolutely trusted. In the second version, external configuration is given higher priority and nss-myhostname only provides a fallback mechanism. This might be suitable in closely controlled networks, for example on a company LAN.
passwd: compat systemd group: compat [SUCCESS=merge] systemd shadow: compat # Either (untrusted network, see above): hosts: mymachines resolve [!UNAVAIL=return] files myhostname dns # Or (only trusted networks): hosts: mymachines resolve [!UNAVAIL=return] files dns myhostname networks: files protocols: db files services: db files ethers: db files rpc: db files netgroup: nis
To test, use glibc's getent tool:
$ getent ahosts `hostname` ::1 STREAM omega ::1 DGRAM ::1 RAW 127.0.0.2 STREAM 127.0.0.2 DGRAM 127.0.0.2 RAW
In this case, the local hostname is omega.