How to Assign a Static Hostname to a Linux Machine

Popular:
LEVEL UP YOUR SERVER SETUP! APPLY AVA AND LAUNCH WITH A 15% DISCOUNT
USE PROMO:

Introduction

A hostname is a unique identifier assigned to a machine on a network. In Linux OS, setting a static hostname ensures consistency, making it easier to manage and identify servers or workstations. This article explains different methods to assign a static hostname on Linux, covering both temporary and permanent changes across various distributions.

Checking the Current Hostname

Before changing the hostname, check the current one using:

hostnamectl

Or simply:

hostname

This will display the existing hostname of your Linux machine.

Most modern Linux distributions (Ubuntu, Debian, CentOS, Fedora) use systemd, which provides the hostnamectl command for managing hostnames.

Changing the Hostname

  1. Set the static hostname:
    sudo hostnamectl set-hostname my-static-hostname
  2. Verify the change:
    hostnamectl

The change is immediate and persists across reboots.

Method 2: Manually Editing /etc/hostname

For distributions that do not use hostnamectl, modify the /etc/hostname file directly.

  1. Open the file in a text editor:
    sudo nano /etc/hostname
  2. Replace the existing name with your desired hostname.
  3. Save the file and exit (CTRL + X → Y → ENTER).
  4. Apply the change:
    sudo systemctl restart systemd-hostnamed

    Or reboot the system:

    sudo reboot

Method 3: Updating /etc/hosts

After changing the hostname, update /etc/hosts to reflect the new name.

  1. Edit the file:
    sudo nano /etc/hosts
  2. Modify the line containing the old hostname:
    127.0.0.1   my-static-hostname
  3. Save and exit.

This prevents networking issues and ensures proper hostname resolution.