How to Change Hostname on Ubuntu 21.04

Displaying the Current Hostname

To find out your current system name by running the following command.

hostnamectl

Output:

[email protected]:~# hostnamectl
   Static hostname: vps.server.com
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 408de4acd0a039b7ebea51f4608a0ab1
           Boot ID: bb8ccfc8e2824c569d170a176974495b
    Virtualization: kvm
  Operating System: Ubuntu 21.04
            Kernel: Linux 5.11.0-16-generic
      Architecture: x86-64

Changing the System Hostname

Now that you know the current hostname, you can change the hostname by using the following command and Optionally you can also set the pretty hostname as follows.

hostnamectl set-hostname crowncloud.net

hostnamectl set-hostname "crowncloud production server" --pretty

And also /etc/hosts file should be edited to successfully change Ubuntu server name.

vi /etc/hosts

Output:

127.0.0.1 localhost
127.0.1.1 crowncloud.net

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

Then replace the old name with the new, then save the file and exit.

Ubuntu servers might need to install cloud-init. If it is installed you will also need to edit the cloud.cfg file.

apt install cloud-init

Once the cloud-init is installed need to find "preserve_hostname: false" line in the follwoing configuration file "/etc/cloud/cloud.cfg" and change it to true.

vi /etc/cloud/cloud.cfg

preserve_hostname: true

Save the file and exit,

Verify the change

To verify the hostname has been fully changed, enter the "hostnamectl" command:

hostnamectl

Output:

[email protected]:~# hostnamectl
   Static hostname: crowncloud.net
   Pretty hostname: crowncloud production server
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 408de4acd0a039b7ebea51f4608a0ab1
           Boot ID: bb8ccfc8e2824c569d170a176974495b
    Virtualization: kvm
  Operating System: Ubuntu 21.04
            Kernel: Linux 5.11.0-16-generic
      Architecture: x86-64
[email protected]:~#