How to change the hostname in Ubuntu

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:

hostnamectl

which will show similar output to this:

nick@hh1gb-chi-vm:~$ hostnamectl
Static hostname: linuxandcaffeine
Icon name: computer-vm
Chassis: vm
Machine ID: 9a2cc821400d64e2b6ef407nc17dcf68
Boot ID: b37cai306ab84812ad55ff8a002iff52
Virtualization: kvm
Operating System: Ubuntu 18.04.2 LTS
Kernel: Linux 4.18.0-20-generic
Architecture: x86-64

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):

127.0.0.1 localhost
127.0.1.1 linuxandcaffeine

# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Save /etc/hosts and exit (if you’re using nano to edit then press CTRL+O to save and CTRL+X to exit).

Completion

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.

Leave a Reply

Your email address will not be published. Required fields are marked *