How to set and change the hostname

Topic: Servers linux

Summary

Set the system hostname persistently with hostnamectl or by editing /etc/hostname and /etc/hosts. Use this when provisioning a server, cloning a VM, or fixing duplicate hostnames so the machine has a unique, predictable name for logs and SSH.

Intent: How-to

Quick answer

  • hostnamectl set-hostname NEWNAME sets the hostname immediately and persists it; no reboot needed. Verify with hostnamectl status or hostname.
  • Ensure /etc/hosts has an entry for 127.0.0.1 NEWNAME or 127.0.1.1 NEWNAME so local resolution works; add the FQDN if you use it.
  • On systems without hostnamectl, write NEWNAME to /etc/hostname and run hostname NEWNAME; reboot or restart services that cached the old name.

Prerequisites

Steps

  1. Set hostname with hostnamectl

    sudo hostnamectl set-hostname myserver; hostnamectl status shows Static hostname. The change is immediate and stored in /etc/hostname; no reboot required.

  2. Update /etc/hosts

    Edit /etc/hosts; ensure 127.0.0.1 or 127.0.1.1 is associated with the new hostname (and FQDN if used). Prevents resolution issues for local services and sudo.

  3. Verify and propagate

    hostname and hostnamectl; restart critical services (e.g. syslog, cron) if they logged the old name; reconnect SSH sessions to see the new name in prompts.

Summary

Set the hostname with hostnamectl so it persists across reboots; update /etc/hosts so the name resolves locally. Use this when provisioning, cloning, or correcting duplicate hostnames.

Prerequisites

Steps

Step 1: Set hostname with hostnamectl

sudo hostnamectl set-hostname myserver
hostnamectl status

The static hostname is written to /etc/hostname and applied immediately.

Step 2: Update /etc/hosts

Edit /etc/hosts so the hostname resolves:

127.0.1.1   myserver myserver.example.com

Step 3: Verify and propagate

Run hostname and hostnamectl. Restart services that may have cached the old name; new SSH sessions will show the new hostname.

Verification

  • hostname and hostnamectl status show the new name; getent hosts myserver resolves to 127.0.0.1 or 127.0.1.1.

Troubleshooting

hostnamectl not found — Write the hostname to /etc/hostname and run hostname NEWNAME; reboot to apply fully. sudo slow or wrong hostname — Ensure /etc/hosts has the hostname for 127.0.0.1 or 127.0.1.1.

Next steps

Continue to