Ubuntu 18.04: Hostname and domain configuration

This article will describe hostname and domain configuration.

1 Write short hostname to /etc/hostname and write domain to /etc/hosts

If you write FQDN like foobar.example.com to /etc/hostname, hostname command seems to be worked well, but Debian says "This file should contain only the system hostname, not a fully qualified domain name".

Combination /etc/hostname and /etc/hosts will work not only Debian but also on RedHat.

$ sudo hostnamectl set-hostname foobar
$ echo '127.0.0.1 foobar.example.com foobar' | sudo tee -a /etc/hosts
127.0.0.1 foobar.example.com foobar
$ hostname
foobar
$ hostname -f
foobar.example.com

If you leave hostname and domain settings to DHCP server, you should set hostname to localhost and remove FQDN from /etc/hosts.

2 Hostname configuration with hostnamectl

The hostnamectl command set hostname. It is smart to set domain with /etc/hosts. Compared to writing /etc/hostname and using hostname command, hostnamectl absorbs the difference in Linux distribution.

$ sudo hostnamectl set-hostname <HOSTNAME>

3 Hostname configuration with "Settings"

Open "Settings" and input hostname to "Computer Name" in "Sharing". "." and " " will be replaced to "-".

0001_Settings-Sharing-ComputerName.png

4 Domain configuration with /etc/hosts

If there is the FQDN includes machine's hostname in /etc/hosts, that domain will be used as machine's domain.

$ cat /etc/hosts
<snip>
127.0.0.1 <HOSTNAME>.<DOMAIN> <HOSTNAME>
<snip>

For example, this appends the following FQDN.

$ cat /etc/hosts
<snip>
127.0.0.1 foobar.example.com foobar
127.0.0.1 barfoo.hiroom2.com barfoo
<snip>

If changing hostname to "foobar", domain will be "example.com".

$ sudo hostnamectl set-hostname foobar
$ hostname -f
foobar.example.com

If changing hostname to "barfoo", domain will be "hiroom2.com".

$ sudo hostnamectl set-hostname barfoo
$ hostname -f
barfoo.hiroom2.com

5 Update hostname with DHCP server

If DHCP server provides hostname with "option host-name" and machine's hostname is "localhost", machine's hostname will be updated to hostname provided by DHCP server.

$ hostname -f
foobar.example.com
$ sudo hostnamectl set-hostname localhost
$ hostname -f # DHCP server has send host-name to this machine already.
kvm-ubuntu-1804-hostname.hiroom2.com

6 Update domain with DHCP server

If DHCP server provides domain with "option domain-name" and there is no FQDN includes machine's hostname, domain provided by DHCP server will be used as machine's domain.

$ hostname
foobar
$ grep foobar /etc/hosts
$ hostname -f
foobar.hiroom2.com