I Know This Error Is Infuriating
You change your hostname, reboot, and it's back to the old one. I've been there. It's like the server has a mind of its own. But the fix is simple once you know where to look.
The Quick Fix: Two Commands
On most modern Linux systems (Ubuntu 18.04+, CentOS 7+, RHEL 7+, Debian 9+), the hostnamectl command is your friend. Run these:
sudo hostnamectl set-hostname new-hostnameThat sets it immediately. But to make it stick, you also need to edit the hostname file. Here's how.
Step 1: Edit /etc/hostname
sudo nano /etc/hostnameReplace the old hostname with new-hostname. Save and exit.
Step 2: Check /etc/hosts
Open it:
sudo nano /etc/hostsLook for a line starting with 127.0.0.1. It should look like this:
127.0.0.1 localhostDon't put your new hostname there. That's a common mistake. If you see 127.0.0.1 new-hostname, remove it. Your hostname should only be on the line with your static IP (if configured) or not at all. This tripped me up the first time too.
Why This Works
When you reboot, the system reads /etc/hostname to set the hostname. If that file has the old name, hostnamectl changes are overwritten. Also, /etc/hosts can interfere if you put the hostname incorrectly. The fix is to make sure /etc/hostname has the right name and /etc/hosts doesn't have conflicting entries.
Less Common Variations
CentOS or RHEL 6 and older
These use /etc/sysconfig/network. Look for a line like:
HOSTNAME=old-hostnameChange it to your new hostname. The hostnamectl command doesn't work on these versions.
Debian 8 or older
Same as above – edit /etc/hostname and /etc/hosts. Also check /etc/hostname is not a symlink. I once saw a symlink pointing to a config file that was regenerated on boot. That was a fun hour.
Cloud images (AWS, DigitalOcean, etc.)
Cloud-init often sets hostname on first boot. If you're on a cloud VM, run:
sudo hostnamectl set-hostname new-hostnameThen edit /etc/cloud/cloud.cfg and set preserve_hostname: true. Otherwise, cloud-init will override your changes on reboot.
Prevention: Make It Stick
After you fix it, test. Reboot and run hostname. Should show your new name. If not, check /etc/hostname and /etc/sysconfig/network again. Also, don't forget to update any services that depend on the hostname (like mail servers or databases). They might cache the old name.
One more thing – if you're using Docker or LXC containers, the hostname is often set inside the container config. That's a different beast. For standard Linux servers, the steps above are all you need.
Still stuck? Drop the error message and your distro in the comments. I'll help you track it down.