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), oracle, debian, kali linux.

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.
Save the file and exit the editor.

3. System has not been booted with systemd as init system.
Enable systemd via /etc/wsl.conf

4. Copy below code & paste it in wsl.conf file.


[boot]
systemd=true
[user]
default=username

5. 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

6. 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 *