Friday 10 June 2022

Get WSL 2 Distro /etc/hosts File Updated via Windows hosts file

 The hosts file in /etc/hosts is allowing the WSL distros to map IP addresses to domain names before going to domain name servers, similar to the Windows hosts file available in C:\Windows\System32\drivers\etc\hosts. You can maintain WSL host file sperately from your Windows host file or let your WSL host file to be generated automatically (the default behavoir) by using contents in your Windows hosts file. 

To view the current contents of your WSL host file located in /etc/hosts you can run cat /etc/hosts.


Now let's think mydemodomain should resolve to your local IP address. Let's update the Windows host file accordingly (To update Windows hosts file make  a copy of it from C:\Windows\System32\drivers\etc\hosts to you desktop. Edit the hosts file copied to desktop and save it. Then copy and paste it back to C:\Windows\System32\drivers\etc\hosts. You may be prompt with request for admin previlleges ).  See the updated Windows hosts file below.


Use a command prompt or PowerShell window in administrator mode and execute wsl --shutdown which will stop WSL. Then reopen WSL terminal cat /etc/hosts to view /etc/hosts.


If you want to prevent Windows hosts update to automatically update howst file in your WSL distro you can add following content to the /etc/wsl.conf file.

[network]

generateHosts = false

In your WSL terminal or in VS Code terminal while connected to the Distro, run sudo vim /etc/wsl.conf and add the above content to the file. 


Now, if you update the Widows hoata file as below wth new demo IP map, it will not get updated in the WSL distro /etc/hosts file, after wsl --shutdown and reopening the WSL terminal.



If we set generateHosts = true in the /etc/wsl.conf file and resart WSL, the distro it will get the /etc/hosts file updated with Windows hosts file entries.




No comments:

Popular Posts