Introduction

This tutorial will guide you through the process of changing the hostname on an Ubuntu 18.04 system.

You need to use the hostnamectl command to see or set the Ubuntu 18.04 LTS system’s host name. The host name or computer name is usually at system startup in /etc/hostname file. Open the terminal application and type the following commands to set or change hostname or computer name on Ubuntu.

The hostname is set at the time when the Ubuntu operating system is installed or if you are spinning up a virtual machine it is dynamically assigned to the instance at startup.

The method described in this guide will work without the need of restarting your system.

How to display the current Ubuntu hostname

Use hostnamectl command to retrieve a current system hostname:

$ hostnamectl
   Static hostname: ubuntu1804
         Icon name: computer-vm
           Chassis: vm
        Machine ID: ceb8b579440b472899a95049f8a61e05
           Boot ID: 3f73eea15fb34a38937488149143d9d3
    Virtualization: oracle
  Operating System: Ubuntu Bionic Beaver
            Kernel: Linux 4.13.0-32-generic
      Architecture: x86-64

Change Hostname

Run Below command with required hostname at the end

$ sudo hostnamectl set-hostname mytestserver

Futhermore, check for the existence of /etc/cloud/cloud.cfg configuration.

sudo nano /etc/cloud/cloud.cfg
# This will cause the set+update hostname module to not operate (if true)
preserve_hostname: true

If the file exists edit the file and change the settings within: The above will preserve your new hostname after reboot.

Next, confirm the new hostname:

$ hostnamectl 
   Static hostname: mytestserver
         Icon name: computer-vm
           Chassis: vm
        Machine ID: ceb8b579440b472899a95049f8a61e05
           Boot ID: 3f73eea15fb34a38937488149143d9d3
    Virtualization: oracle
  Operating System: Ubuntu Bionic Beaver
            Kernel: Linux 4.13.0-32-generic
      Architecture: x86-64

You may also want to update your /etc/hosts file so the system can resolve itself via new host name. Open /etc/hosts file and and append your new hostnane right after the old hostname:

$ cat /etc/hosts
127.0.0.1       localhost
127.0.1.1       mytestserver

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

In this tutorial, we have shown you how to easily change your Ubuntu server hostname without restarting the machine.