A hostname is a custom name created by the user. This name also differentiates a particular device from others within a local network. Below we have guided you step-wise on how to change hostname using the command line on Ubuntu
Displaying the Current Hostname
To do so use either hostnamectl or hostname command:
hostname
Output:
root@oymog-hostname:~# hostname
oymog-hostname
root@oymog-hostname:~#
hostnamectl
Output:
root@oymog-hostname:~# hostnamectl
Static hostname: oymog-hostname
Icon name: computer-container
Chassis: container
Machine ID: b041ed357e814794b0796f9f6b644865
Boot ID: 0dbb61c0f887423480ccc30919695a09
Virtualization: wsl
Operating System: Ubuntu 22.04.3 LTS
Kernel: Linux 5.15.146.1-microsoft-standard-WSL2
Architecture: x86-64
root@oymog-hostname:~#
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 new-hostname
Upon changing your hostname using the hostnamectl command no system reboot is required to apply the hostname change.
sudo hostnamectl set-hostname oymog.com
sudo hostnamectl set-hostname oymog.com --static
sudo hostnamectl set-hostname oymog.com --transient
Using the above command we are setting our new hostname as “oymog.com”.
And next /etc/hosts
file should be edited to successfully change the Ubuntu server name.
nano /etc/hosts
From:
127.0.0.1 localhost
127.0.1.1 oymog-hostname
To:
127.0.0.1 localhost
127.0.1.1 oymog.com
Then replace the old name with the new, then save the file, and exit.
Verify the Changes
To verify the hostname has been fully changed, enter the hostnamectl command:
hostnamectl
Output:
[email protected]:~# hostnamectl
Static hostname: oymog.com
Icon name: computer-container
Chassis: container
Machine ID: b041ed357e814794b0796f9f6b644865
Boot ID: 0dbb61c0f887423480ccc30919695a09
Virtualization: wsl
Operating System: Ubuntu 22.04.3 LTS
Kernel: Linux 5.15.146.1-microsoft-standard-WSL2
Architecture: x86-64
[email protected]:~#