Skip to main content
In this lesson you will learn how to view and change the system hostname, manage local host-to-IP mappings, and verify name resolution on a Linux system. Correct hostname configuration and reliable name resolution are important because many services and networked applications depend on resolving hostnames correctly.
A dark presentation slide reading "Demo" with the subtitle "Configuring Hostnames and Name Resolution" on the left. The right side shows a large empty dark panel with a small "Copyright KodeKloud" in the top-right.

Displaying the current hostname

  • Use the hostname command to print the current (runtime) hostname.
  • The persistent hostname is stored in /etc/hostname.
  • For detailed metadata and the canonical static/present hostname, use hostnamectl (systemd).
Example session:

Setting a new hostname

To change the persistent hostname (updates /etc/hostname automatically), use:
Verify the change:
Note: hostnamectl updates the static hostname and is the recommended method on systemd-based distributions.

Local name resolution — /etc/hosts

  • The file /etc/hosts contains local host-to-IP mappings. This file is consulted before DNS when files appears before dns in /etc/nsswitch.conf.
  • Each line should contain an IP address, then one or more hostnames separated by whitespace.
Example (with a commented correction and a real mapping):
If you update a mapping (for example change node1 to node5 at a new IP), save /etc/hosts. The system will then resolve that hostname using the updated entry.

Testing resolution with ping

After editing /etc/hosts, use ping to confirm the hostname resolves to the expected IP:
Tip: You can map arbitrary hostnames (e.g., google.com) to a chosen IP in /etc/hosts for testing, but avoid doing this for public hostnames in production.

Use getent to test resolver lookups

getent queries the system name service switch and respects the lookup order defined in /etc/nsswitch.conf. Use it to verify how the system resolves names without sending ICMP traffic:
This shows the resolver result as the system sees it, following nsswitch.conf rules.

Name resolution order — /etc/nsswitch.conf

The file /etc/nsswitch.conf defines the order the system uses to resolve different databases, including hosts. A typical hosts line is:
Meaning:
  1. files — check /etc/hosts
  2. dns — query DNS servers
  3. myhostname — fallback to local machine name methods
Example /etc/nsswitch.conf excerpt (with authselect comments corrected):

Quick reference

Entries in /etc/hosts take precedence over DNS when files appears before dns in /etc/nsswitch.conf. Use /etc/hosts for local overrides and testing, but avoid modifying it for public hostnames unless you understand the implications.
This concludes the demo on configuring hostnames and managing local name resolution.

Watch Video