How to Set Hostname on Ubuntu 22.04/Debian 11

Preface

We may have to change the default hostname of Ubuntu 22.04/Debian 11 to,

  • Identify a host: a meaningful hostname helps you to quickly identify the host. For example, when I log into node-1fb26c7, I have no idea about the host at all; but if the hostname is changed toltt-database, I immediately see what’s going on there;
  • Avoid unexpected rebooting or disk swiping: suppose we have two servers for MySQL and backups, namely, node-1fb26c7 and node-5fbf6c2, respectively. And we were going to swipe the backup server (node-5fbf6c2), and to optimize the filesystem. But we accedentally logged into the MySQL node, and formatted the whole disk, and puff, all data was gone!
  • Prevent programs from malfunctioning: some applications, say Apache HTTP Server, use hostname to look up the server’s FQDN. What is more, even sudo command throws warning if the hostname does not match an IP.

Brief

This article will show you,

  1. how to change the hostname on Ubuntu 22.04/Debian 11;
  2. how to change the hostname on CentOS 7 and AlmaLinux 8; and,
  3. how to check if the hostname has been updated successfully.

Take Action!

Suppose the current hostname is old-host and we are going to change it to node-mysql.

You may login as root (or a sudo user), and execute commands shown below. Don’t forget to replace the fake hostname with the real one. (Password may be required if you are a sudo user rather than root.)

# define the new hostname here, please replace 'node-mysql' to the real one
export NEW_HOSTNAME='my-node'

# install prerequisites if necessary
sudo bash -c 'grep -E "Debian|Ubuntu" /etc/os-release && (systemctl status dbus.service dbus.socket || (apt update && apt install -y dbus))'
sudo bash -c 'grep -E "CentOS|AlmaLinux|RockyLinux" /etc/os-release && (systemctl status dbus.service dbus.socket || (yum install -y dbus))'


# change the hostname to the new one
sudo hostnamectl set-hostname "${NEW_HOSTNAME}"

# make sure the local address matches the new hostname
sudo bash -c "echo '127.0.0.1 ${NEW_HOSTNAME}' >> /etc/hosts"

# validate if the hostname is successfully changed, it should prints the new hostname
bash -c "if [[ \"`hostname`\" == \"${NEW_HOSTNAME}\" ]]; then echo \"Hostname has been successfully changed to '$(hostname)'\"; else echo \"Failed to change hostname, which is '$(hostname)' now\"; fi"

Caution: you may have to re-login to see the change, as the current prompt is sticky to the original settings when it was open.

Leave a Reply

Your email address will not be published. Required fields are marked *