How to change your VPS hostname and mailname on Ubuntu 16.04 LTS permanently

Today we want to set the host name of our VPS so that it still existed after a reboot. Some vendors reset the hostname after a reboot, so we bypass with a script that makes the adjustments for us.

First we have to create a file called set_vps_hostname.service in /etc/systemd/system/

sudo nano /etc/systemd/system/set_vps_hostname.service

content:

[Unit]
Description=Set my hostname on boot
Before=rsyslog.service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/set_vps_hostname

[Install]
WantedBy=multi-user.target

Now we have to create the script set_vps_hostname (adjust the hostname to yours) :

sudo nano /usr/local/bin/set_vps_hostname

content:

#!/bin/bash
HOSTNAME=www.markus-blog.de # <---adjust hostname here
[ -f /etc/hostname ] && echo $HOSTNAME > /etc/hostname
[ -f /etc/HOSTNAME ] && echo $HOSTNAME > /etc/HOSTNAME
[ -f /etc/mailname ] && echo $HOSTNAME > /etc/mailname
[ -f /etc/sysconfig/network ] && sed -i.hebackup s/HOSTNAME=".*"/HOSTNAME="$HOSTNAME"/ /etc/sysconfig/network
/bin/hostname $HOSTNAME
[ -f /etc/my.resolv.conf ] && cp /etc/my.resolv.conf /etc/resolv.conf
[ -f /etc/my.hosts ] && cp /etc/my.hosts /etc/hosts
exit 0

Now we make the script executable:

sudo chmod +x /usr/local/bin/set_vps_hostname

Next we want to set the hostname in /etc/hosts file too:

sudo nano /etc/hosts

change the name to the hostname we need and copy the file to /etc/my.hosts to make it persistent:

sudo cp /etc/hosts /etc/my.hosts

if we use our own nameserver, we had to adjust the resolv.conf too:

sudo nano /etc/resolv.conf

and we copy the file to /etc/my.resolv.conf:

sudo cp /etc/resolv.conf /etc/my.resolv.conf

Now we have to enable our service and reboot to set the hostname with the following command (please be aware, this command will Reboot your VPS):

sudo systemctl daemon-reload && sudo systemctl enable set_vps_hostname.service && sudo systemctl start set_vps_hostname.service && sudo systemctl restart rsyslog && sudo reboot

after reboot we check the hostname with:

cat /etc/hostname
cat /etc/mailname

That’s it and have fun 🙂

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert