What’s a hostname?
A hostname is a name that identifies your computer or server on a network and it can be a simple name consisting of just one word, for example: computer, or it can be a phrase like my-server-name, or it can be a FQDN (Fully Qualified Domain Name) such as mycomputer.linuxandcaffeine.com.
Note: This tutorial will also work with Debian too!
Changing the hostname with hostnamectl
You can easily change your hostname in Ubuntu by starting a terminal and using the hostnamectl command.
For example, say you would like to change your hostname to “linuxandcaffeine” – you can use the hostnamectl command with the set-hostname option to do that, like this:
sudo hostnamectl set-hostname linuxandcaffeine
and to verify that your hostname was changed you can use the hostnamectl command again with:
which will show similar output to this:
Static hostname: linuxandcaffeine
Icon name: computer-vm
Machine ID: 9a2cc821400d64e2b6ef407nc17dcf68
Boot ID: b37cai306ab84812ad55ff8a002iff52
Operating System: Ubuntu 18.04.2 LTS
Kernel: Linux 4.18.0-20-generic
Note: You might have to logout and log back in to see the hostname change.
Finish by editing /etc/hosts
After using hostnamectl to change your hostname, you should also configure /etc/hosts with your new hostname.
Go ahead and open /etc/hosts now with
sudo nano /etc/hosts
and change every instance of your old hostname to your new hostname (in this example I will still be using the “linuxandcaffeine” hostname):
# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
Save /etc/hosts and exit (if you’re using nano to edit then press CTRL+O to save and CTRL+X to exit).
After following this quick tutorial, you should now have your new hostname all setup! If you have any questions or comments (or if you need help setting up a FQDN instead) then please leave a comment below or you can contact me privately and I will do my best to help you out.
Are you running a server with cloud-init?
If you’re performing a hostname change on a server running cloud-init then you must perform the following steps, otherwise the hostname change won’t stick.
Open up /etc/cloud/cloud.cfg
sudo nano /etc/cloud/cloud.cfg
and change preserve_hostname from false to true
Then make sure to save your changes to /etc/cloud/cloud.cfg and exit.