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.

v-change-sys-hostname meuhostname.com

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/change_hostname.sh

Add the following commands:


#!/bin/bash
# Script to automatically change the hostname

NEW_HOSTNAME="meuhostname.com"

echo "$NEW_HOSTNAME" > /etc/hostname
sed -i "s/.*127.0.0.1.*/127.0.0.1   $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/change_hostname.sh

Create a systemd service to execute the script:

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

Add the following content:


[Unit]
Description=Change hostname to meuhostname.com.br

[Service]
Type=oneshot
ExecStart=/usr/local/bin/change_hostname.sh

[Install]
WantedBy=multi-user.target

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.