Persistent Hostname

I’m going to share a simple solution for those using a VPS with a persistent hostname. In my case, simply changing the hostname conventionally didn’t work.


It works momentarily, but if I ever need to restart the server, the hostname is automatically lost due to my DataCenter’s configurations, which enforce hostname management rules.

In this case, what works for me is the following: let’s create a file in the following path:

sudo vim /usr/local/bin/

Add the following commands:

# Script to automatically change the hostname


echo "$NEW_HOSTNAME" > /etc/hostname
sed -i "s/.**/   $NEW_HOSTNAME localhost/" /etc/hosts
hostnamectl set-hostname "$NEW_HOSTNAME"

Here’s the script that sets the NEW_HOSTNAME variable with the desired new hostname and then updates the localhost and hosts files with the new hostname. It also utilizes hostnamectl to configure the hostname.

Grant execution permission to the script:

sudo chmod +x /usr/local/bin/

Create a systemd service to execute the script:

sudo vim /etc/systemd/system/change-hostname.service

Add the following content:

Description=Change hostname to



Reload systemd and enable the service:

sudo systemctl daemon-reload
sudo systemctl enable change-hostname.service

There you go, now when you restart the system, the hostname should be set correctly.