Linux

How to set the hostname on Ubuntu

To set or change the hostname on an Ubuntu system, follow these steps:

1. Change Hostname Temporarily

To change the hostname for the current session (until the system is rebooted), you can use the hostname command:

sudo hostname new-hostname

Replace new-hostname with the desired hostname. This change will not persist after a reboot.

2. Change Hostname Permanently

To make the hostname change permanent, you need to update a couple of configuration files:

a. Edit /etc/hostname

1. Open the /etc/hostname file in a text editor:

sudo nano /etc/hostname

2. Replace the existing hostname with your new hostname.

3. Save the file and exit the editor (in Nano, press CTRL+X, then Y, then ENTER).

#b. Edit /etc/hosts

1. Open the /etc/hosts file in a text editor:

sudo nano /etc/hosts

2. Find the line that starts with 127.0.1.1 and update the hostname there. It will look something like this:

127.0.1.1   old-hostname

    Change old-hostname to your new hostname.

3. Save the file and exit the editor.

3. Apply Changes

To apply the changes without rebooting, you can use the hostnamectl command:

sudo hostnamectl set-hostname new-hostname

This command updates the hostname and ensures that it’s reflected in various system services.

4. Reboot (Optional)

Although using hostnamectl or updating the files should apply changes immediately, rebooting the system ensures all services are using the new hostname:

sudo reboot

Summary

- Temporary change: sudo hostname new-hostname
- Permanent change: Edit /etc/hostname and /etc/hosts, then use hostnamectl or reboot.

By following these steps, you should be able to set a new hostname on your Ubuntu system effectively.