Changing the hostname of your Ubuntu system via the command line is a straightforward process that can be useful for various administrative tasks, like network configuration or system identification. Here's a step-by-step guide:
1. Check Current Hostname
Before making any changes, it's good to verify your current hostname:
hostname
This command will display the hostname of your system.
2. Temporary Change (Until Reboot)
If you need to change the hostname only for the current session, you can use:
sudo hostname new-hostname
Replace new-hostname
with your desired hostname. This change will be lost upon reboot.
3. Permanent Change
For a permanent change that persists after reboot, you'll need to edit several files:
/etc/hosts: This file maps hostnames to IP addresses.
sudo nano /etc/hosts
Look for lines containing the old hostname and change them to reflect the new hostname. Typically, you'll find something like:
127.0.1.1 old-hostname
Change this to:
127.0.1.1 new-hostname
/etc/hostname: Contains the system's hostname.
sudo nano /etc/hostname
Replace the existing hostname with your new one, then save and exit (in nano, press Ctrl+O
, then Enter
to save, and Ctrl+X
to exit).
4. Apply the Changes
After modifying these files, apply the changes:
sudo hostnamectl set-hostname new-hostname
This command updates the hostname and also ensures that other system files are updated accordingly.
5. Verify the Change
To ensure the hostname has been changed:
hostname
Or:
hostnamectl
This will show you the current settings including the new hostname.
6. Reboot
For all changes to take full effect across all services:
sudo reboot
Additional Tips
- Cloud Environments: If your Ubuntu system runs in a cloud environment like AWS, Azure, or Google Cloud, you might also need to update the hostname via the cloud provider's management console or CLI tools to ensure it's reflected in their systems.
- DNS: If your hostname needs to be resolved via DNS, ensure you update your DNS records with your new hostname.
- Security: Remember that changing your hostname can affect security configurations like SSH keys that might have been set to accept connections only from the old hostname.
By following these steps, you can effectively change your Ubuntu system's hostname from the command line, ensuring both temporary and permanent changes as needed for your administrative or personal use cases. Remember to handle system configurations cautiously, especially in production environments.