How to access to the web server which running on WSL(Windows Subsystem for Linux) from local network How to access to the web server which running on WSL(Windows Subsystem for Linux) from local network linux linux

How to access to the web server which running on WSL(Windows Subsystem for Linux) from local network


Please follow the steps mentioned in the link shared by @erazerbrecht and run your HTTP server by providing your ip address (instead of using localhost) and port number.

example:
root@teclast:~# python3 -m http.server -b 192.168.1.178 8000Serving HTTP on 192.168.1.178 port 8000 (http://192.168.1.178 :8000/) ...

Otherwise you can also do this instead of following the link:
1. Goto Windows defender firewall
2. select inbound
3. create new rule; next
4. select Program as a rule type; next
5. select All Program; next
6. select allow the connection; next
7. check all 3 (Domain, Private, Public); next
8. provide rule a name
9. finish
10. Your are good to go


None of the existing answers work for me, as WSL2 is running in its own VM and has its own network adapter. You need some sort of bridge or port forwarding for non-localhost requests to work (i.e. from another host on the same network).

I found a script in https://github.com/microsoft/WSL/issues/4150 that worked to resolve the issue:

$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';if( $found ){  $remoteport = $matches[0];} else{  echo "The Script Exited, the ip address of WSL 2 cannot be found";  exit;}#[Ports]#All the ports you want to forward separated by coma$ports=@(80,443,10000,3000,5000);#[Static ip]#You can change the addr to your ip config to listen to a specific address$addr='0.0.0.0';$ports_a = $ports -join ",";#Remove Firewall Exception Rulesiex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";#adding Exception Rules for inbound and outbound Rulesiex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";for( $i = 0; $i -lt $ports.length; $i++ ){  $port = $ports[$i];  iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";  iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";}

Running this script from an elevated/admin Powershell session did the trick for me. This allows accessing the WSL2 service running on a port to be accessible from the Windows host IP at that same port.


In your VM, execute ifconfig

You will see your IP in the first section (eth0:) inet x.x.x.x

This x.x.x.x is the IP you have to put in your browser.