Recommended Method: Using hostnamectl (Systemd-based Debian Systems)
The hostnamectl command is the most reliable and modern way to permanently set a hostname in Debian (especially for systemd-based systems, which includes all recent Debian versions like Bookworm, Bullseye, etc.). This method automatically updates system files and applies changes without requiring manual edits to multiple files.
hostnamectl to check the existing hostname. The output will display the static hostname (the permanent one) and other details.sudo hostnamectl set-hostname new-hostname (replace new-hostname with your desired name, e.g., debian-vm). This command updates the static hostname in the system’s systemd configuration./etc/hosts (Optional but Recommended):/etc/hosts file maps IP addresses to hostnames. To avoid resolution issues, edit it to replace the old hostname with the new one. Run sudo nano /etc/hosts, locate the line starting with 127.0.1.1 (or 127.0.0.1), and change the old hostname to new-hostname. For example:127.0.0.1 localhost
127.0.1.1 debian-vm # Replace 'old-hostname' with 'debian-vm'
::1 localhost ip6-localhost
sudo reboot) or the systemd-hostnamed service (sudo systemctl restart systemd-hostnamed) to apply the new hostname. Most modern Debian systems do not require a full reboot for hostnamectl changes to take effect.hostnamectl again or use hostname to confirm the new hostname is displayed.Alternative Method: Manual Editing of Configuration Files
If you prefer manual configuration or are using an older Debian version without hostnamectl, you can directly edit system files. This method also ensures permanent changes.
/etc/hostname:sudo nano /etc/hostname) and replace the existing hostname with new-hostname. Save and exit the editor./etc/hosts:127.0.1.1 line in /etc/hosts to point to new-hostname (see step 3 in the hostnamectl method).networking service:sudo systemctl restart networking
Or, if using NetworkManager:sudo systemctl restart NetworkManager
Alternatively, reboot the virtual machine.Temporary Hostname Change (Not Recommended for Virtual Machines)
If you need a temporary hostname change (e.g., for testing), you can use the hostname command. This change will reset after a system reboot.
sudo hostname new-hostname (replace new-hostname with your desired name).hostname to confirm the change. Note that this does not modify /etc/hostname or /etc/hosts, so it is not persistent.Key Notes for Virtual Machines