During the installation of Linux on your Servers, you are asked to set a hostname. You may have either skipped that step, or you’ve realized the hostname you’ve set will not work. Either of those being the case, what do you do? Fortunately–within the world of Linux–setting or changing a hostname is very, very easy. I’m going to show you how to set (or reset) that hostname in two ways: Manually and with the hostnamectl command. I’ll be demonstrating on a daily build of Ubuntu 18.04, but both of these methods will work on Ubuntu 16.04 as well.
The manual method
This method will work on nearly any Linux distribution.
Before we get into this method, do note it will require you to reboot the server. Otherwise, the new hostname will not go into effect and you could wind up with some random issues–depending upon what your server is used for.
Open up a terminal window. Unless you’ve modified your bash prompt, you should see at least part of the hostname in the prompt. If not, you can find out what your hostname is by issuing the command hostname (Figure A).
To modify the hostname, we need to modify two files. For the first, issue the command sudo nano /etc/hostname. In this file you will see a single line that contains your system hostname. Edit that line to reflect the new hostname. Once you’ve done that, save and close the file.
Next, issue the command sudo nano /etc/hosts. In this file, you’ll want to change any instance of the old hostname to reflect the new hostname. Unless you’ve modified that file, you should only see one instance (Figure B).
Once you’ve made the necessary modification, save and close the file. Reboot the server and the hostname will take effect. You’re good to go.
Using this method, you won’t be required to reboot the server. The hostnamectl command can be found on any Linux machine that uses systemd.
Issue the command hostnamectl. You should see a bit of information about your system (Figure C).
To change the hostname with this command, the syntax is:
hostnamectl set-hostname NEWNAME
Where NEWNAME is the new hostname. This command will automatically change and set the /etc/hostname file (Figure D). The only thing left to do is edit the /etc/hosts file to reflect the new hostname (as described above). With this method, no reboot is necessary.
And that is all you need to change the hostname of your Ubuntu Linux servers. If you’re okay with rebooting your server or your Linux machine doesn’t make use of systemd, go with the first method. If you’d rather not reboot and your system does make use of systemd, go with the second method.