Changing server name or hostname on a Linux machine

June 23, 2020

When you create a virtual machine on Amazon AWS or another cloud provider, you may realize that the hostname was assigned automatically (which is the case with EC2 VMs on AWS if you don't attach a specific tag to the server) or is incorrect.

You can easily check current hostname on Linux servers by running the following commands in the terminal:

uname -n
hostname -s

Change the hostname on a running system

hostname command which we used before also allows updating its value. Run hostname NEW_HOSTNAME to update VM's hostname to NEW_HOSTNAME. The change will take effect immediately but will be reverted as soon as the server reboots.

Setting the hostname permanently (older Debian based systems)

In order to permanently change the hostname of Debian based system (including Ubuntu) you need to update the file located in /etc/hostname. Note that it will most likely be owned by a root user and have -rw-r--r-- permissions, which means only the owner (root) can write to it.

You can run the following: (replace vim with your favourite text editor if it's different)

sudo vim /etc/hostname

Provide the sudo password if needed, make a change, save and exit the editor by typing :wq. Then run the following command to apply the changes:

sudo /etc/init.d/hostname.sh

Setting the hostname on modern Linux systems

If the solution above doesn't work or there's no /etc/init.d/hostname.sh script on your system, you can use the hostnamectl command instead:

sudo hostnamectl set-hostname NEW_HOSTNAME

Finally, check the hostname status:

hostnamectl status