logo

How to permanently set hostname in ubuntu without restart

Hostname is the name of the machine which is used to identify a specific host within a computer network. It can be any levels deep. It could be as simple as john or complex as john.example.com. If the hostname is not set correctly then the programs such as mail servers and other computers in the network will issue warnings or will fail completely.

By default hostname is set by the system automatically, but in some cases we want to change that name for convenience and we can do that easily with the following steps:

1. First change the current hostname

$ hostname MY_NEW_NAME

This change is temporary, until the system reboot. But it's good for having no downtime.

2. Update the hostname file /etc/hostname

We can do that by either of the following ways:

# For newer distribution, that use `SystemD` init
$ sudo hostnamectl set-hostname MY_NEW_HOSTNAME
# For older distribution, `SysV` init 
$ sudo echo "my-new-hostname" > /etc/hostname

3. Add a new record to /etc/hosts file

$ sudo echo "127.0.0.1 my-new-hostname" > /etc/hosts
# or directly open `/etc/hosts` file 
$ sudo nano /etc/hosts

After the changes your new /etc/hosts file look like this:

127.0.0.1       localhost
127.0.0.1       guest
127.0.1.1       my-new-hostname
# other entries below
## ..
## ..