Changing the hostname on WSL2

Edit /etc/wsl.conf in the WSL2:

sudo vi /etc/wsl.conf

Add these lines (i.e. changing hostname to “PC”). generateHosts = false to disable WSL to auto generate /etc/hosts.

[network]
hostname = PC
generateHosts = false

Edit /etc/hosts to match with the configured hostname.

sudo vi /etc/hosts

Close all WSL terminals, and open a Command Prompt (not WSL terminal). Note: shutdown nor reboot won’t work on WSL:

wsl.exe --shutdown

Open a WSL terminal, and see the new hostname to “PC”:

test@PC:~$

Note: hostnamects set-hostname won’t work on WSL: