Это руководство проведет вас через процесс изменения имени хоста в системе CentOS 7.
Имя хоста задается во время установки операционной системы CentOS или если вы запускаете виртуальную машину, оно динамически назначается экземпляру при запуске.
Методы, описанные в этом руководстве, будут работать без перезагрузки вашей системы.
Прежде чем приступить
Прежде чем продолжить это руководство, убедитесь, что вы вошли в систему как пользователь с привилегиями sudo .
Общие сведения об именах хостов
Имя хоста — это метка, которая идентифицирует машину в сети. Вы не должны использовать одно и то же имя хоста на двух разных машинах в одной сети.
Есть три класса hostname
: static
, pretty
и transient
.
static
— Традиционное имя хоста, которое может быть установлено пользователем и хранится в/etc/hostname
файле.pretty
— Имя хоста в свободной форме UTF8, используемое для представления пользователю. НапримерLinuxize's desktop
.transient
— Динамическое имя хоста, поддерживаемое ядром, которое может быть изменено сервером DHCP или mDNS во время выполнения. По умолчанию это то же самое, что иstatic
имя хоста.
Рекомендуется использовать полностью квалифицированное имя домена ( FQDN
) для обоих static
и transient
имена , такие как host.example.com
.
Показать текущее имя хоста
Чтобы просмотреть текущее имя хоста, введите следующую команду:
hostnamectl
Как видно из изображения выше, текущее имя хоста установлено на localhost.localdomain
.
Измените имя хоста
Метод 1: с помощью hostnamectl
команды
В CentOS 7 мы можем изменить имя хоста системы и соответствующие настройки с помощью команды hostnamectl
, синтаксис следующий:
sudo hostnamectl set-hostname host.example.com
sudo hostnamectl set-hostname "Your Pretty HostName" --pretty
sudo hostnamectl set-hostname host.example.com --static
sudo hostnamectl set-hostname host.example.com --transient
Например, если мы хотим изменить статическое имя хоста системы на host.linuxize.com
, мы можем использовать следующую команду:
sudo hostnamectl set-hostname host.linuxize.com
Чтобы установить красивое имя хоста Linuxize's desktop
, введите:
sudo hostnamectl set-hostname "Linuxize's desktop" --pretty
Команда hostnamectl
не производит вывода. В случае успеха возвращается 0, в противном случае — ненулевой код ошибки.
Способ 2: с помощью nmtui
команды
nmtui
— это текстовый пользовательский интерфейс для NetworkManager, который также можно использовать для изменения имени хоста.
Для запуска nmtui
утилиты выполните следующую команду:
sudo nmtui
Используйте клавиши со стрелками для навигации по параметрам, выберите Set system hostname
и нажмите Enter
:
Установите новое имя хоста:
Нажмите Enter, чтобы подтвердить изменение имени хоста:
Наконец, перезапустите systemd-hostnamed
службу, чтобы изменения вступили в силу:
sudo systemctl restart systemd-hostnamed
Метод 3: с помощью nmcli
команды
nmcli
— это инструмент командной строки для управления NetworkManager, который также можно использовать для изменения имени хоста.
Чтобы просмотреть текущий тип имени хоста:
sudo nmcli general hostname
Чтобы изменить имя хоста, host.linuxize.com
используйте следующую команду:
sudo nmcli general hostname host.linuxize.com
Наконец, перезапустите systemd-hostnamed
службу, чтобы изменения вступили в силу:
sudo systemctl restart systemd-hostnamed
Проверить изменение
Чтобы убедиться, что имя хоста было успешно изменено, используйте hostnamectl
команду:
hostnamectl
Ваше новое имя хоста будет напечатано на консоли:
Static hostname: host.linuxize.com
Pretty hostname: Linuxize's desktop
Icon name: computer-vm
Chassis: vm
Machine ID: 52d6807a6ae34327871ae568f7a1387e
Boot ID: 4f747d0280d3402abed870d18b6e9a7a
Virtualization: kvm
Operating System: CentOS Linux 7 (Core)
CPE OS Name: cpe:/o:centos:centos:7
Kernel: Linux 3.10.0-693.11.6.el7.x86_64
Architecture: x86-64
Вывод
В этом руководстве мы показали вам 3 различных метода изменения имени хоста вашего сервера CentOS 7 без перезагрузки компьютера
Introduction
A hostname is simply the name a server goes by on a network. Setting a unique hostname is an excellent way to quickly find and identify different servers on your network.
There are three 3 types of hostnames.
- The static hostname is the most important one, and it’s stored in the /etc/hostname file. This hostname is used among machines to identify a particular server.
- The pretty hostname got its name because it allows for more characters and punctuation. It’s more user-friendly, but since it uses non-standard characters, it is not permitted for machine code. The pretty hostname is stored in the /etc/machine-info directory.
- The transient hostname is one maintained in the Linux kernel. It is dynamic, meaning it will be lost after a reboot. This approach might be useful if you have a minor job requiring a temporary hostname, but you don’t want to risk making a permanent change that might be confusing.
Prerequisites
- Server running CentOS 7
- Access to a user account with root privileges
- Terminal window (Menu > Applications > Utilities > Terminal)
- A text editor, like Vim
Step 1: Check Existing Hostname
Before you start, it is advised to check what your current hostname is. Type the following command in the console to find out:
hostnamectl
The output should return the static hostname, as well as a list of other information about your network configuration and operating system.
Step 2: Set a New Static Hostname
As CentOS 7 only allows Fully Qualified Domain Names (FQDNs), double-check the hostname you plan to use.
Acceptable values include:
- Lower-case letters a to z
- Numbers 0 to 9
- Periods and hyphens
- Hostnames must be between 2 and 63 characters
- Hostnames must start and end with a number or letter
Type in the following command in the terminal:
hostnamectl set-hostname my.new-hostname.server
Note: Make sure to replace my.new-hostname.server
with your chosen hostname.
Step 3: Check the Hostname
Next, verify the hostname by using the following command again:
hostnamectl
The console should display the new hostname.
Step 4: Edit the /etc/hosts File
Start by opening the hosts file by typing:
sudo vim /etc/hosts
In the text editor, look for the line that begins with 127.0.0.1 (the IP address that refers to the system you are working on). It should read:
127.0.0.1 localhost localhost.localdomain localhost 4 localhost4.localdomain4 old.hostname
Change the entry old.hostname
to my.new-hostname.server
– and spell it the same as in Step 2.
Save the file and exit.
Step 5: Reboot and Check CentOS 7 machine hostname
Restart your system. Open a console window, and run:
hostnamectl
It should display your new hostname.
You can also use your text editor to open and verify your /etc/hostsfile
. It should still have your new hostname listed.
Step 6 (Optional): Using a Pretty Hostname
To use a «pretty» hostname type the following command:
hostnamectl set-hostname "My Boss's Hostname"
Make sure you have the quotation marks.
Once that completes, check the hostname:
hostnamectl status
The console should return a list of information. Check the Static hostname and Pretty hostname lines – they should look like this:
Static hostname: mybossshostname
Pretty hostname: My Boss's Hostname
By putting the hostname in quotes, you’re telling the system to use the complex characters inside the quotes as a pretty hostname.
This enables you to avoid character restrictions for static hostnames.
But you still need a FQDN hostname for the machine to understand. Fortunately, CentOS is smart enough to remove or change any unacceptable characters and render the static hostname automatically.
Step 7 (Optional): Setting a Transient Hostname
Fist, open the console and type the following:
sudo hostnamectl -transient set-hostname temporary.hostname
You can check the hostname in the same way you did earlier, with the hostnamectl
or hostnamectl status
command.
This change will last until you reboot the machine.
You can use this command with any type of hostname (Static, Pretty, or Transient) as an option with the double-hyphen.
Just use the double-hyphen to indicate what you want:
sudo hostnamectl --prettyset-hostname "Pretty Hostname"
or
sudo hostnamectl --staticset-hostname temporary.hostname
Conclusion
To set or change a hostname in CentOS 7 is fairly straightforward.
If you are a more advanced user, you can try out other methods as well. One way is editing the /etc/hostname file with a text editor. Alternatively, you can run the nmtui
tool at the command prompt, which will launch a little graphical tool to change the hostname.
A guide on how to change or set the hostname is also available for other Linux distributions like Ubuntu 18.04.
Введение | |
Узнать имя своего хоста | |
Изменить имя хоста | |
С помощью hostnamectl | |
pretty hostname | |
hosts | |
alias | |
На хостинге | |
Похожие статьи |
Введение
Имя хоста — это уникальная метка, которая идентифицирует машину в сети.
Должна существовать таблица соответствия между hostname и
IP адресом
это нужно для для маршрутизации пакетов.
Хост может иметь несколько имён, но предпочтительным является вариант, когда имя одно.
Существует три класса hostname : static , pretty и transient .
-
static — традиционное имя хоста, которое может быть установлено пользователем и хранится в
/etc/hostname - pretty — имя хоста UTF8 в свободной форме, используемое для представления пользователю. Например HeiHei’ host.
- transient — динамическое имя хоста, поддерживаемое ядром, которое может быть изменено сервером DHCP или mDNS во время выполнения. По умолчанию это то же самое, что и static имя хоста.
Рекомендуется использовать полное доменное имя ( FQDN ) как для static и для transient имен, таких как host.example.com .
Так как CentOS 7 поддреживает только Fully Qualified Domain Names (FQDNs),
советую тщательно проверить hostname, который вы планируете использовать.
Допустимые значения:
- Строчные буквы от a до z
- Цифры от 0 до 9
- Точки и дефисы
- Hostnames может быть от 2 до 63 символов
- Hostnames должен начинаться и заканчиваться цифрой или буквой
Узнать имя своего хоста
Существует несоколько способов узнать имя своего хоста.
Часто для этого достаточно просто посмотреть в терминал
Пример моего терминала
[andrei@localhost Downloads]$
andrei — это имя пользователя
localhost — это имя хоста
Downloads — имя текущей директории
Посмотреть порядок можно выполнив
echo $PS1
[u@h W]$
u — пользователь
h — хост
W — Working Directory — Рабочая диретория
Другие способы
hostname
localhost.localdomain
hostname -f
localhost
uname -n
localhost.localdomain
hostnamectl
Static hostname: localhost.localdomain
Icon name: computer-vm
Chassis: vm
Machine ID: 35e254eda578c54084b96e06d5f285cf
Boot ID: afb44fef8d764f30bb89550849b02fde
Virtualization: kvm
Operating System: CentOS Linux 7 (Core)
CPE OS Name: cpe:/o:centos:centos:7
Kernel: Linux 3.10.0-1160.36.2.el7.x86_64
Изменить имя хоста
С помощью команды hostname
hostname dns-server
hostname
dns-server
Если заново открыть терминал изменения будут видны в командной строке.
[andrei@dns-server~]$
Это имя хоста сохранится только до перезагрузки системы
Если выполнить hostnamectl видно, что
помянелось только динамическое имя хоста
hostnamectl
Static hostname: localhost.localdomain
Transient hostname: dns-server
Icon name: computer-vm
Chassis: vm
Machine ID: cff8a80b9c356243b5238452511a8ade
Boot ID: 64d9ddab85ec4c219ac46c6a2940e628
Virtualization: kvm
Operating System: CentOS Linux 7 (Core)
CPE OS Name: cpe:/o:centos:centos:7
Kernel: Linux 3.10.0-1160.42.2.el7.x86_64
Architecture: x86-64
Если изучить файл
hostname
, также можно увдиеть отсутствие изменений.
cat /etc/hostname
localhost.localdomain
С помощью hostnamectl
hostnamectl set-hostname dns-server.andrei.com
hostname
dns-server.andrei.com
Это постоянное изменение. Т.е. новое имя хоста имеет класс persistent.
cat /etc/hostname
dns-server.andrei.com
pretty name
Чтобы задать pretty name нужно воспользоваться кавычками
hostnamectl set-hostname «andrei’s.host.com»
hostnamectl
Static hostname: andreis.host.com
Pretty hostname: andrei’s.host.com
Icon name: computer-vm
Chassis: vm
Machine ID: cff8a80b9c356243b5238452511a8ade
Boot ID: 64d9ddab85ec4c219ac46c6a2940e628
Virtualization: kvm
Operating System: CentOS Linux 7 (Core)
CPE OS Name: cpe:/o:centos:centos:7
Kernel: Linux 3.10.0-1160.42.2.el7.x86_64
Architecture: x86-64
Появилось pretty hostname а static hostname такое же
, но без запрещенных символов
В /etc/hostname отображается только static hostname
cat /etc/hostname
andreis.host.com
pretty hostname можно увидеть в файле
/etc/machine-info
cat /etc/machine-info
PRETTY_HOSTNAME=»andrei’s.host.com»
hosts
Изучить информацию об именах других хостов можно в файле
hosts
В моём примере в сети есть два хоста:
dns-server.andrei.com
с IP адресом
192.168.56.149
host113.andrei.com с IP адресом
192.168.56.113
Зайдём на него с помощью
ssh
и посмотрим, есть ли у него записи об именах других хостов в сети.
Для наглядности я теперь буду показываеть приглашение терминала чтобы было видно имя хоста.
[andrei@dns-server~]$ ssh andrei@192.168.56.113
Выполним ping по IP
[andrei@host113 ~]$ ping 192.168.56.149
PING 192.168.56.149 (192.168.56.149) 56(84) bytes of data.
64 bytes from 192.168.56.149: icmp_seq=1 ttl=64 time=0.650 ms
64 bytes from 192.168.56.149: icmp_seq=2 ttl=64 time=0.731 ms
^C
— 192.168.56.149 ping statistics —
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.650/0.690/0.731/0.048 ms
По IP пингуется успешно
И ping по hostname
[andrei@host113 ~]$ ping dns-server.andrei.com
ping: dns-server.andrei.com: Name or service not known
host113 не знает как разрешить имя
dns-server.andrei.com
Это неудивительно — ведь в файле
hosts
нет про него никаких записей. Проверим содержимое:
[andrei@host113 ~]$ cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
Добавим запись о dns-server.andrei.com
sudo vi !$
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.56.149 dns-server.andrei.com
Повторим ping
[andrei@host113 ~]$ ping dns-server.andrei.com
PING dns-server.andrei.com (192.168.56.149) 56(84) bytes of data.
64 bytes from dns-server.andrei.com (192.168.56.149): icmp_seq=1 ttl=64 time=0.698 ms
64 bytes from dns-server.andrei.com (192.168.56.149): icmp_seq=2 ttl=64 time=0.735 ms
64 bytes from dns-server.andrei.com (192.168.56.149): icmp_seq=3 ttl=64 time=0.739 ms
^C
— dns-server.andrei.com ping statistics —
3 packets transmitted, 3 received, 0% packet loss, time 2001ms
rtt min/avg/max/mdev = 0.698/0.724/0.739/0.018 ms
Теперь всё работает
alias
Чтобы не писать длинные имена хостов можно придумать alias
Формат следующий
IP FQDN ALIAS
FQDN — Fully Qualified Domain Name — полностью определённое имя домена.
192.168.56.149 dns-server.andrei.com vbdns
[andrei@host113 ~]$ ping vbdns
PING dns-server.andrei.com (192.168.56.149) 56(84) bytes of data.
64 bytes from dns-server.andrei.com (192.168.56.149): icmp_seq=1 ttl=64 time=0.619 ms
64 bytes from dns-server.andrei.com (192.168.56.149): icmp_seq=2 ttl=64 time=0.674 ms
^C
— dns-server.andrei.com ping statistics —
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.619/0.646/0.674/0.037 ms
Обратите внимание на dns-server.andrei.com
Хоть пинг и был по алиасу, ответ идёт как от static fqdn
Если поменять порядок так, что vbdns идёт первым а FQDN dns-server.andrei.com вторым, но
dns-server.andrei.com будет считаться алиасом
192.168.56.149 vbdns dns-server.andrei.com
В таком случае ответ будет идти от vbdns
[andrei@host113 ~]$ ping vbdns
Или
[andrei@host113 ~]$ ping dns-server.andrei.com
PING vbdns (192.168.56.149) 56(84) bytes of data.
64 bytes from vbdns (192.168.56.149): icmp_seq=1 ttl=64 time=0.721 ms
64 bytes from vbdns (192.168.56.149): icmp_seq=2 ttl=64 time=1.01 ms
^C
— vbdns ping statistics —
2 packets transmitted, 2 received, 0% packet loss, time 1004ms
rtt min/avg/max/mdev = 0.721/0.866/1.012/0.148 ms
Это может стать важным при работе с сертификатами
На хостинге
Как добавить соответствие IP адреса и домена сайта
Настройка сети в CentOS | |
Создать новый интерфейс | |
CentOS | |
Компьютерные сети | |
ip | |
hostname | |
DNS | |
route: Маршруты/Роутер | |
Firewall | |
iptables | |
netstat | |
iftop: Мониторинг сети | |
nethogs: Мониторинг сети | |
tc: Контроль за трафиком | |
iperf: Измерение скорости сети | |
uuidgen: uuid для сетевого интерфейса | |
SCP: обмен файлами; | |
SSH: удалённый доступ | |
Сокеты в C |
A computer hostname represents a unique name that gets assigned to a computer in a network in order to uniquely identify that computer in that specific network. A computer hostname can be set to any name you like, but you should keep in mind the following rules:
- hostnames can contain letters (from a to z).
- hostnames can contain digits (from 0 to 9).
- hostnames can contain only the hyphen character
( – )
as a special character. - hostnames can contain the dot special character
( . )
. - hostnames can contain a combination of all three rules but must start and end with a letter or a number.
- hostnames letters are case-insensitive.
- hostnames must contain between 2 and 63 characters long.
- hostnames should be descriptive (to ease identifying the computer purpose, location, geographical area, etc on the network).
In order to display a computer name in CentOS 7/8 and RHEL 7/8 systems via console, issue the following command. The -s
flag displayed the computer short name (hostname only) and the -f
flag displays the computer FQDN in the network (only if the computer is a part of a domain or realm and the FQDN is set).
# hostname # hostname -s # hostname -f
You can also display a Linux system hostname by inspecting the content of /etc/hostname file using the cat command.
# cat /etc/hostname
In order to change or set a CentOS 7/8 machine hostname, use the hostnamectl command as shown in the below command excerpt.
# hostnamectl set-hostname your-new-hostname
In addition to hostname command, you can also use hostnamectl command to display a Linux machine hostname.
# hostnamectl
In order to apply the new hostname, a system reboot is required, issue one of the below commands in order to reboot a CentOS 7 machine.
# init 6 # systemctl reboot # shutdown -r
A second method to set up a CentOS 7/8 machine hostname is to manually edit the /etc/hostname file and type your new hostname. Also, a system reboot is necessary in order to apply the new machine name.
# vi /etc/hostname
A third method that can be used to change a CentOS 7/8 machine hostname is by using the Linux sysctl interface. However, using this method to change machine name results in setting-up the machine transient hostname.
The transient hostname is a special hostname initialized and maintained only by the Linux kernel as an auxiliary machine name in addition to he static hostname and doesn’t survive reboots.
# sysctl kernel.hostname # sysctl kernel.hostname=new-hostname # sysctl -w kernel.hostname=new-hostname
To display machine transient hostname issue the below commands.
# sysctl kernel.hostname # hostnamectl
Finally, the hostnamectl command can be used to achieve the following hostname setups: –pretty, –static, and –transient.
Although there are other more specific ways to change a Linux machine hostname, such as issuing nmtui command or manually editing some configuration files specific to each Linux distribution (/etc/sysconfig/network-scripts/ifcfg-ethX for CentOS), the above rules are generally available regardless of the used Linux distribution.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Setting a proper hostname on a server is the first thing you should do after installing a new server. Most web panels, like cpanel or Vestacp, requires you to have a Fully qualified domain name for your hostname. A fully qualified domain name is in the form of server1.example.com or panel.example.com.
Now to the important question. What is a hostname?
A hostname is a free form string up to the length of 64 characters. It should not begin or end with a dot. Also, can’t use two dots immediately following each other. You can choose any name for your hostname. But the best practice is to choose a fully qualified domain name as your hostname. for example server1.example.com or panel.example.com.
Hostname Types.
CentOS 7 supports three types of Host Names:
Static hostname – The static host name is assigned or chosen by the user and is stored in /etc/hostname file.
Transient or Dynamic hostname – The transient/dynamic hostname is maintained by the kernel and assigned by DHCP and mDNS server at run time.
Pretty hostname – It is a free form UTF -8 hostname for the presentation to the user. For example, “Server 1 of DebYum”.
Red Hat recommends that both static and transient names match the fully-qualified domain name (FQDN) used for the machine in DNS, such as host.example.com.
Change server hostname in CentOS 7.
If you want to change your server hostname to a new one then you should make sure that it is persistent. Means it can survive a reboot.
The process of setting up a new hostname in CentOS 7 is easy. There are many ways to change server hostname in CentOS 7. For example, you can use the command line or Text User Interface tools like NMTUI to change your hostname.
I prefer using the command line to manage hostnames on my server.
Here is a list of different ways to manage your hostname.
- Edit various files to change the hostname.
- Use hostnamectl command to set/change the new hostname
- Use the nmcli command to set/change the new hostname.
Method #1: Edit various files to manage your hostname.
Update the /etc/hostname file on your RHEL 7 or Centos 7 Linux instance with the new hostname.
[root@panel ~]# vi /etc/hostname
panel.www.debyum.com
Update the /etc/sysconfig/network file on RHEL 7 or CentOS 7 Linux instance.
[root@panel~]# vi /etc/sysconfig/network
# Created by anaconda
HOSTNAME=panel.www.debyum.com
Check the Hostname of your server.
[root@panel ~]# hostname
panel.www.debyum.com
Method #2: Use hostnamectl command to manage your hostname.
Set static hostname on CentOS 7.
root@panel:~# hostnamectl set-hostname --static Server1.www.debyum.com
The transient name is assigned by DHCP and mDNS server at run time.
Set pretty hostname on CentOS 7.
root@panel:~# hostnamectl set-hostname "Server 1 of Debyum"
Restart the systemd-hostnamed service.
root@panel:~# systemctl restart systemd-hostnamed
Reboot your server to make things permanent.
Check your hostname settings.
root@server1:~# hostnamectl status Static hostname: Server1.www.debyum.com Pretty hostname: Server 1 of Debyum Transient hostname: Server1 Icon name: computer-vm Chassis: vm Machine ID: 153a217486fe4jsu4r9u228db67ed581 Boot ID: 7fbe3ecfff094w9e81fr55c6a1bf3fe6 Virtualization: kvm Operating System: CentOS Linux 7 (Core) CPE OS Name: cpe:/o:centos:centos:7 Kernel: Linux 4.8.6-x86_64-linode78 Architecture: x86-64
Method #3: Use the nmcli command to manage your hostname.
First of all, check the hostname using the nmcli command:
root@engy:~# nmcli general hostname
engy.www.debyum.com
Set a fully qualified domain name via nmcli command as root.
root@engy:~# nmcli general hostname panel.www.debyum.com
Check the new hostname.
root@engy:~# nmcli general hostname
panel.www.debyum.com
Set a short name as your hostname using the nmcli command. The command is same as setting any kind of hostname in nmcli. (short or FQDN)
root@engy:~# nmcli general hostname panel
Check the new hostname in CentOS 7.
root@engy:~# nmcli general hostname
panel
To force hostnamectl to notice the change in the static hostname, restart hostnamed as root:
root@engy:~# systemctl restart systemd-hostnamed
Thanks for visiting this Page and have a Great day 🙂 .
A hostname is a human-readable string that helps people refer to a computer by a familiar name, rather than by a number or unwieldy descriptors like, «the third one from the bottom of the second-to-last rack.» Often, a hostname is set during the installation process, but there are times when it needs to be changed. On Linux, there are many ways to set a hostname, and this article aims to cover them all.
Before exploring the tools related to hostnames, though, you must understand the different contexts in which the term is used. There are potentially two designators of a system’s hostname: the computer’s administrator (a laptop’s owner, or a server’s root user) and the network (depending on protocols and settings). This factor can lead to confusion, because you might look at your computer’s hostname and see one value, only to find that the same computer is referred to as something different over the network.
There’s a historical reason for this situation. Long ago, before DNS, hosts on a network had to be defined locally in the file /etc/hosts
. If there were 31 hosts on a network and a new one was added, then 32 hosts had to update their /etc/hosts
file to reflect the correct IP address and corresponding hostname for each of their neighbors. This process didn’t scale well for bigger networked systems such as the World Wide Web (the Internet), and so DNS was invented, and the concept of hostnames largely was abstracted away from local computers to instead be managed by the network.
Today, the important hostname is the one the network uses. The hostname value in /etc/hosts
is often set to localhost
by default.
With this context in mind, here are all the different ways to manipulate a hostname on Linux.
[ Free download: Advanced Linux commands cheat sheet. ]
Change all three names with hostnamectl
The hostnamectl
command from systemd
can manipulate three varieties of hostnames:
- Transient: Received from network configuration.
- Static: Provided by the kernel.
- Pretty: Provided by the user.
A transient hostname can change as needed to avoid name collisions. For instance, if you name your computer penguin
but there’s already another host with that name on the network, your network hostname becomes penguin-1
.
Static and pretty hostnames are a little like local variables: They’re used for activities occurring on the local machine, mostly as a convenience for the user, along with applications that need to know whether they’re running locally or remotely (for example, over a forwarded X session).
When invoked without any arguments, hostnamectl
returns the static and pretty names, plus some system information:
$ hostnamectl
Static hostname: penguin
Pretty hostname: Penguin VM
Icon name: computer-vm
Chassis: vm
Machine ID: 418d9ce8ead44bbfb6970c0d356b89bf
Boot ID: fb3a310237ef41f88b1c62c26f19065a
Virtualization: kvm
Operating System: Fedora 30 (Workstation Edition)
CPE OS Name: cpe:/o:fedoraproject:fedora:30
Kernel: Linux 5.0.9-301.fc30.x86_64
Architecture: x86-64
$ sudo hostnamectl set-hostname --pretty "Web dev test environment"
$ sudo hostnamectl set-hostname --static webdev-test-env
$ hostnamectl
Static hostname: webdev-test-env
Pretty hostname: Web dev test environment
[...]
Change the static and pretty names in the GUI with GNOME Settings
If you want to set the static and pretty names in a desktop application, use GNOME Settings. To launch GNOME Settings, go to the Activities menu in the upper left corner of your GNOME desktop. Type Settings
into the search field, or click the Show Applications icon on the left dock and find Settings in the application icons as shown below:
$ hostnamectl
Static hostname: rockhopper-computer
Pretty hostname: rockhopper computer
[...]
Change the static name with cockpit
Fedora, CentOS, and RHEL systems feature a web console application called Cockpit for monitoring and configuring local and remote machines. Using Cockpit, you can change the static hostname for your own machine, or any machine you administer (as long as it has Cockpit enabled).
First, install and enable Cockpit:
$ sudo dnf install cockpit
[...]
$ sudo systemctl enable --now cockpit
In the web console, click the System tab in the left column. Click the entry for Host name and edit the Pretty Host Name and (static) Real Host Name:
$ sudo echo "galapagos" > /etc/hostname
$ hostnamectl
Static hostname: snares
Pretty hostname: rockhopper web console computer
[...]
Change the static name in the hostname
file
You can also set the static hostname manually by editing /etc/hostname
. This file contains exactly one line by default. If you have not changed the hostname yet, then that line probably reads localhost.localdomain
. If you have used hostnamectl
to change the hostname already, then this file reflects that change.
Editing this file manually is not necessarily recommended, because it doesn’t update all the other hostname values the way hostnamectl
does. For example:
$ sudo echo "galapagos" > /etc/hostname
$ hostnamectl
Static hostname: galapagos
Pretty hostname: rockhopper computer
Transient hostname: rockhopper-computer
[...]
Change the static name with nmcli
Another way to change a static hostname is through the command line interface for Network Manager, nmcli
:
$ sudo nmcli general hostname emperor
$ hostnamectl
Static hostname: emperor
Pretty hostname: rockhopper computer
Transient hostname: rockhopper-computer
[...]
Change the transient name with sysctl
The sysctl
command allows you to configure kernel parameters while Linux is running (that is, instead of at boot time). Your computer’s transient hostname is a kernel parameter, so you can modify it with this command:
$ sudo sysctl kernel.hostname=humboldt
$ hostnamectl
Static hostname: emperor
Pretty hostname: rockhopper computer
Transient hostname: humboldt
[...]
Change the transient name with hostname
The hostname
command from the util-linux
package is a simple tool to query and set the transient hostname.
To query your current hostname:
$ hostname
humboldt
$ sudo hostname fjordland
$ hostnamectl
Static hostname: emperor
Pretty hostname: rockhopper computer
Transient hostname: fjordland
Be careful with /etc/hosts
The /etc/hosts
file is mostly historic, although it is used by some applications and protocols, and can be a useful method for creating shortcuts to hosts you use often. You can use it to set a hostname, but usually, you’re just creating an alias to localhost
at IP address 127.0.0.1
(your computer’s network loopback address).
For example, if you change /etc/hosts
from the default entries like this:
$ cat /etc/hosts
127.0.0.1 magellanic magellanic.localdomain magellanic magellanic.localdomain4
::1 magellanic magellanic.localdomain magellanic magellanic.localdomain6
$ ping -c 1 localhost
PING localhost(magellanic (::1)) 56 data bytes
64 bytes from magellanic (::1): icmp_seq=1 ttl=64 time=0.182 ms
[...]
$ ping -c 1 magellanic
PING magellanic(magellanic (::1)) 56 data bytes
64 bytes from magellanic (::1): icmp_seq=1 ttl=64 time=0.181 ms
[...]
$ hostnamectl
Static hostname: emperor
Pretty hostname: rockhopper computer
Transient hostname: fjordland
Follow the conformity convention
As you can tell from the iterations within this article, a computer’s hostname can get confusing should you use too many methods to set it, or if you change it frequently. While nothing enforces uniformity across hostname types, it’s a convention to keep everything the same on each computer.
Choose a memorable name and use it for your pretty name. Let the static and transient names be derived from that. Just as importantly, in a large network, choose meaningful names. For instance, all upper management computers may be named after a D&D monster, while all computers in the IT department may be named after a famous starship, and so on. Using a naming schema helps avoid name collisions and provides context to an otherwise dizzying list of network hosts.