For now (03.2022) to access from outside an app running on WSL 2, we need to do the following:
Make rules in the firewall for accepting incoming (and maybe also outgoing) connexions on the protocol and port on which the app is running (e.g. TCP/80)
Get WSL's vm IP: hostname -I
As said on this page (Accessing a WSL 2 distribution from your local area network (LAN)), use this IP address to add, in Windows, a proxy that listens on the port and redirects to WSL's vm. This is done by the following command in a PowerShell running as administrator:
netsh interface portproxy add v4tov4 listenport=80 listenaddress=0.0.0.0 connectport=80 connectaddress=192.168.101.100
Where 192.168.101.100
is vm's IP from hostname -I
and 80
the port we want to open to the outside.
As WSL's IP changes when rebooted, this should be automated in a PowerShell script, where the previous proxy is removed and a new one is set to the current IP. All credit goes to Edwindijas on Github from who's script this one is heavily inspired:
$ports=@(80,21,22) # the ports you want to open
$addr='0.0.0.0';
$wslIP = bash.exe -c "hostname -I"
$found = $wslIP -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if(! $wslIP -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') {
echo "WSL's IP cannot be found. Aborting";
exit;
}
$portsStr = $ports -join ",";
iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $portsStr -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $portsStr -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=$wslIP";
}