Setting hostname in Linux

In the systemd Environment there has been an architectural change and the systemd daemon controlling all the essential processes

root 1 0 0 Apr15 ? 00:00:12 /usr/lib/systemd/systemd --switched-root --system --deserialize 32

We can make use of the hostnamectl command to immediately reflect the system hostname change.


Command to get the current hostname on Linux:

[vamshi@server02 ~]$ sudo hostnamectl 
   Static hostname: server02.linuxcent.com
   Pretty hostname: SERVER02
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 2338f55840d640689fc5ac4b356b160c
           Boot ID: 418256281d2f4e11822809dde7c1b09e
    Virtualization: kvm
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-1062.18.1.el7.x86_64
      Architecture: x86-64

As you can see the current hostname is set to SERVER02

The file /etc/hostname also used to have the same effect but on the cloud systems this is dynamically generated and doesn’t hold true on cloud and tends to get overwritten after reboot.
On the general DataCenter or PC environment we can use the static files to populate the hostnames and make them permanent:

$ cat /etc/sysconfig/network
HOSTNAME=node2.linuxcent.com

But only /etc/hostname file is given importance since the systemd version and updating this ensures persistence.

$ cat /etc/hostname 
node02.linuxcent.com

 

Process to set or change the hostname in Linux Commandline:

The systemd provides a sophisticated command hostnamectl to set the hostname, It will also update the static file /etc/hostname and ensure the changes are permanent across reboots.

$ sudo hostnamectl set-hostname node02.Linuxcent

To get the hostname along with FQDN

[vamshi@server02 ~]$ hostname --fqdn
node02.linuxcent.com
[vamshi@node02 ~]$ sudo hostnamectl status 
   Static hostname: node02.linuxcent.com
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 2338f55840d640689fc5ac4b356b160c
           Boot ID: 33619e39ea4c4900bd848e13d2a6239e
    Virtualization: kvm
  Operating System: CentOS Linux 7 (Core)
       CPE OS Name: cpe:/o:centos:centos:7
            Kernel: Linux 3.10.0-1062.18.1.el7.x86_64
      Architecture: x86-64

Changing hostname is ubuntu and Debian systems can be done through hostnamectl command

vamshi@debian:~$ hostnamectl 
Static hostname: debian
Icon name: computer-vm
Chassis: vm
Machine ID: b4adcdb84c724856b577524ebbfa0003
Boot ID: 67e1bf27946a4770b8e939f2420d06fd
Virtualization: oracle
Operating System: Debian GNU/Linux 10 (buster)
Kernel: Linux 4.19.0-5-amd64
Architecture: x86-64

Leave a Comment