CentOS 7 has a nice command called hostnamectl. With it we can display the current hostname, and set any of the three types of hostname:
- static hostname (something like example.com)
- transient hostname (anything you like, assigned when using DHCP)
- pretty hostname (something like Jay’s MacBook Pro)
By default, a CentOS installation comes back with localhost.localdomain – but that’s not meaningful if you see lots of localhosts on the same network.
If the IP of the box does not change, we can set the static hostname like this:
hostnamectl sethostname example.com --static
No feedback means good news. Likewise, we can set a hostname if were using DHCP to get an IP address, even though it may change every time we connect. To make sure we retain the same name no matter what IP we get, let’s set the transient hostname like so:
hostnamectl sethostname myserver --transient
Note that we can’t use spaces or special characters with static or transient hostnames as far as I know.
Lucky for us there’s also the pretty hostname, which does support special characters. It doesn’t usually appear anywhere on the command line, but GUIs like to display the pretty name of a machine when available:
hostnamectl sethostame "Jay's MacBook Pro" --pretty
There’s no need to restart anything, the changes are in effect as soon as we hit return after either command.
To see the current hostnames, we can use the status switch:
hostnamectl status Static hostname: example.com Transient hostname: myserver Pretty hostname: Jay's MacBook Pro Icon name: computer-vm Chassis: vm Machine ID: 3d1ed70be1e940efaab8fb63b82822cc Boot ID: b95807c92b904fc192bd086b2596bea5 Virtualization: kvm Operating System: CentOS Linux 7 (Core) CPE OS Name: cpe:/o:centos:centos:7 Kernel: Linux 3.10.0-229.20.1.el7.x86_64 Architecture: x86_64
Thanks to Vivek Gite for this wonderful explanation!