How To Set Hostname In Linux (Ubuntu)

How To Set Hostname In Linux (Ubuntu)

Note:- This only works for ubuntu version (20.04, 22.04, 24.04)

Initialize systemd to set the hostname at boot time.

Here’s how you can do it:

1. Create a systemd Service Unit
Open a terminal and create a new systemd service unit file for setting the hostname:

sudo nano /etc/systemd/system/sethostname.service

2. Add the following lines to the file:


[Unit]
Description=Set Hostname

[Service]
Type=oneshot
ExecStart=/bin/hostnamectl set-hostname your-new-hostname

[Install]
WantedBy=multi-user.target


Replace `your-new-hostname` with your desired hostname.

3. Save the file and exit the editor.

4. Reload systemd and Enable the Service:
Reload systemd to recognize the new service unit file and enable the service:


sudo systemctl daemon-reload
sudo systemctl enable sethostname.service

5. Restart Your System:
Finally, restart your system to apply the changes:

After rebooting, the systemd service should set the hostname during the boot process, ensuring that it persists across reboots.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *