3 Methods To Change the Hostname of Your Linux Machine

February 18, 2020

This tutorial explains 3 methods to change the hostname of your Linux machine.

Check the current hostname

You can use hostname command.

hostname

or use hostnamectl

hostnamectl

change hostname

Change Hostname: Method1

Hostname is configured in /etc/hostname file. So we can manually open this file and change hostname there.

sudo nano /etc/hostname

Delete the current name in this file and enter a new hostname for your Linux box. Save and close this file.

Check hostname again with hostname or hostnamectl command and you will see hostname has changed. If you open a new terminal window, you will also notice the hostname has changed. The new hostname is preserved across system reboots with this method.

Update /etc/hosts file

Another thing we need to do is to update /etc/hosts file.

sudo nano /etc/hosts

Just replace the old hostname with the new hostname. Note that Linux is case sensitive. Then save and close this file.

change hostname

If you don’t update /etc/hosts file, some programs such as sudo don’t know how to resolve the new hostname.

If you change the hostname of a Internet-facing Linux server, the new hostname should resolve to public IP address. If you change the hostname of a Debian or Ubuntu home computer, then the new hostname should resolve to 127.0.1.1.

The Debian installer create 127.0.1.1 <host_name> entry for a system without a permanent IP address. For a system with a permanent IP address, 127.0.1.1 should be replaced by the permanent IP address. 127.0.1.1 uses the loopback interface. In fact, 127.0.0.0/8 (127.0.0.0 ~ 127.255.255.255) is all bound to the loopback interface.

Method 2: Change Hostname with hostnamectl

sudo hostnamectl set-hostname <newhostname>

This command will remove the old hostname from /etc/hostname and put the new hostname in its place. As with the first method, we need to update /etc/hosts file.

Method3: Change Hostname Temporarily

To temporarily change hostname (lost after reboot), use hostname command:

sudo hostname <new-hostname>

This command won’t change the static hostname in /etc/hostname file. It only changes the transient hostname, so the new hostname won’t be preserved across reboots.

The static hostname is stored in /etc/hostname file.

Need help?

Do you need help setting up this on your own service?
Please contact us and we’ll provide you the best possible quote!