Sub topic 7
Setting the hostname and keeping /etc/hosts consistent
This chapter assumes you can use a Linux shell and sudo. It also assumes you know what a fully qualified domain name (FQDN) is. You should know the difference between a name that lives in DNS and a name that lives only on the server. By the end you will set a static hostname, write a matching /etc/hosts, and check that the system agrees with itself.
Three kinds of hostname
A Linux machine can carry up to three names at once. systemd tracks all of them through hostnamed.
| Kind | Where it lives | Purpose |
|---|---|---|
| Static | `/etc/hostname` | The name the system sets at boot. This is the one you configure. |
| Transient | The running kernel | The name currently in use. DHCP or `mDNS` can set it, and it can differ from the static name. |
| Pretty | `/etc/machine-info` | A free-form label for people, such as "Web Server 01". It can contain spaces and capitals. |
On a server you normally manage only the static name. The transient name starts out equal to the static name. If the static name is empty, a DHCP lease or a reverse DNS lookup can supply a transient one. That is one reason a server's name sometimes changes after a reboot without anyone editing a file.
Choosing a name
A hostname is a label, not an address. Follow these rules so that every tool accepts it:
- Use only lowercase letters
a-z, digits, and hyphens. - Do not start or end a label with a hyphen.
- Keep each label to 63 characters or fewer. Keep the whole name to 253 or fewer.
- Prefer a name that describes the role or location, such as
web01, and avoid names that describe the hardware.
There are two common styles for the static hostname:
- Short name:
web01. The domain comes from the search domain in the resolver configuration. - FQDN:
web01.example.com. The domain is part of the name itself.
Both work. Many mail servers, certificate tools, and cluster software read the hostname and expect an FQDN, so this tutorial uses web01.example.com. If your organization has a naming policy, follow it.
Setting the static hostname
Use hostnamectl. It writes /etc/hostname, updates the running kernel, and notifies other services in one step.
sudo hostnamectl set-hostname web01.example.com
hostnamectl --staticThe second command prints the stored value, web01.example.com. Run plain hostnamectl to see all three names, the machine ID, the kernel, and the virtualization type.
Editing /etc/hostname by hand also works. The file holds a single line with the name. If you edit it, the running name does not change until you run sudo hostnamectl set-hostname "$(cat /etc/hostname)" or reboot. Using hostnamectl directly avoids that gap.
To set the pretty name or clear a name, use these options:
sudo hostnamectl set-hostname "Web Server 01" --pretty
sudo hostnamectl set-hostname "" --transientSetting an empty transient name makes the system fall back to the static name.
A shell prompt that was already open keeps showing the old name, because the shell read it at login. Start a new shell, or log out and in, to see the new name in the prompt.
What /etc/hosts does
/etc/hosts is a plain-text file that maps names to addresses on the local machine. The system reads it before it asks DNS, in the default configuration. Each line has an address, then the canonical name, then any aliases. A # starts a comment.
The next chapter explains the lookup order in detail. For now, remember the practical consequence. If a name is in /etc/hosts, the system answers from the file and never contacts a DNS server for that name. That is fast and does not depend on the network. It also means a wrong entry silently overrides correct DNS data.
Writing a consistent /etc/hosts
The server should be able to resolve its own name without DNS. Software starts, logs, and sends mail using the hostname, and a slow or failed lookup of your own name causes long delays at login, in sudo, and in service startup.
Here is a file for the server in this tutorial:
127.0.0.1 localhost
127.0.1.1 web01.example.com web01
192.168.1.50 web01.example.com web01Two conventions appear here, and they are not both needed:
- Debian-style
127.0.1.1. Debian and Ubuntu installers add a line that maps the hostname to127.0.1.1. The purpose is to give a machine without a permanent address a name that still resolves. It is a convention, not a standard. - Static IP. When the server has a fixed address, as it does after the Netplan or NetworkManager chapters, map the name to that address instead.
For a server with a fixed address, the cleaner file is:
127.0.0.1 localhost
192.168.1.50 web01.example.com web01Keep only one of the two mappings for the hostname. If both are present, the first matching line wins for forward lookups, so getent hosts web01 returns 127.0.1.1. Network services that bind or advertise their hostname then give out a loopback address, and other machines cannot reach them. Remove the 127.0.1.1 line when you add the static address line.
Rules for the entries
- Put the FQDN first, then the short name. Tools that do a reverse lookup of an address report the first name on the line, so it should be the full one.
- Use the same address you configured on the interface. If you change the static IP, change this line too.
- Keep
127.0.0.1 localhost. Many programs depend on it. - Do not put the hostname on the
localhostline. That makes the FQDN resolve to loopback and gives the same problem as above. - For IPv6, the usual lines are
::1 localhost ip6-localhost ip6-loopbackand the entries for theff02::multicast groups. Leave the lines the installer created.
Edit the file with a root editor, for example sudo nano /etc/hosts or sudoedit /etc/hosts. Changes take effect immediately. No restart is needed, because the C library reads the file on each lookup.
Cloud images and files that get rewritten
On many cloud images and some provisioning systems, cloud-init manages the hostname and can regenerate /etc/hosts at each boot. You set the name, reboot, and the old name returns.
Check for it:
cloud-init status
grep -R "manage_etc_hosts\|preserve_hostname" /etc/cloud/ 2>/dev/nullIf cloud-init is active, set preserve_hostname: true in a file under /etc/cloud/cloud.cfg.d/, or change the hostname through its configuration. Otherwise it overwrites your work. The setting manage_etc_hosts: true tells it to rebuild /etc/hosts from a template. Either keep that behavior and edit the template, or turn it off.
Other tools can do the same. NetworkManager can set the transient hostname from DHCP unless the static name is set. Configuration management tools such as Ansible or Puppet may also own the file. Find out which system owns the file before you edit it by hand.
Name changes and running services
Changing the hostname on a running server has effects beyond the two files:
- Services that read the name at start, such as mail transfer agents, databases, and web servers with virtual hosts, keep the old name until they restart.
- TLS certificates issued for the old name stop matching. Clients that verify the name will reject the connection.
- Monitoring, logging, and backup systems may track the machine by name, so the history splits at the change.
- DNS records are separate. The
AandPTRrecords for the new name must be created on your DNS server. Editing/etc/hostson the server does not make other machines see the name.
Plan the change for a maintenance window, and restart or reload the services that depend on the name.
The workflow
The order matters. If you change the hostname before /etc/hosts, sudo prints unable to resolve host until you fix the file.
The diagram below shows the order.
Verifying the result
Run these checks. They ask the system the same way programs do.
hostnamectl --static
hostname
hostname -f
getent hosts web01
getent hosts web01.example.comExpected results:
hostnamectl --staticandhostnameprint the name you set.hostname -fprints the FQDN. This command resolves the name to find the domain, so it relies on/etc/hostsor DNS. If it prints onlyweb01or reports "Name or service not known", the hosts entry is missing or in the wrong form.getent hosts web01andgetent hosts web01.example.comboth print192.168.1.50 web01.example.com web01.
Use getent, not nslookup or dig, to test /etc/hosts. dig and nslookup ask DNS directly and ignore the hosts file, so they give a false failure for names that exist only there.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `sudo: unable to resolve host web01` | The hostname has no entry in `/etc/hosts` and DNS cannot answer. | Add the line with the FQDN and short name. |
| `hostname -f` prints `localhost` | The hostname is on the `127.0.0.1` line, or the file is empty. | Move the name to its own line. |
| The name reverts after reboot | `cloud-init` or another tool rewrites the file. | Set `preserve_hostname: true` or edit the tool's configuration. |
| Other machines cannot reach the name | The name exists only in the local `/etc/hosts`. | Create a DNS record on the DNS server. |
| `hostnamectl` rejects the name | The name has an underscore, a space, or an invalid character. | Use only letters, digits, and hyphens. |
Exercise
A server with the static address 192.168.1.50 has the hostname set to web01.example.com, and /etc/hosts contains "127.0.0.1 localhost web01.example.com web01". Running "hostname -f" prints "localhost". Explain why, and write the corrected /etc/hosts.
Show answer
The lookup for the hostname finds the first matching line, and on that line the first name after the address is "localhost", so the canonical name returned is "localhost". The hostname is also mapped to loopback, so other software that advertises the name gives out 127.0.0.1. Corrected file: "127.0.0.1 localhost" on the first line and "192.168.1.50 web01.example.com web01" on the second line. Then run "hostname -f" and "getent hosts web01" to confirm that both print the FQDN with 192.168.1.50.
Exercise
You run "sudo hostnamectl set-hostname db01.example.com" on a server. Afterwards "sudo" prints "unable to resolve host db01". Which file do you edit, which line do you add, and which command confirms the fix?
Show answer
Edit /etc/hosts and add a line that maps the server's address to the new name, for example "192.168.1.60 db01.example.com db01" (use the address that is on the interface). Confirm with "getent hosts db01", which should print that line. The error appeared because the system looked up the new name, found no entry in /etc/hosts, and DNS had no record for it.