Port forwarding in WSL2
One of the projects I’m contributing to is using a Windows development environment with WSL2. It’s great to have a Linux machine running seamlessly with the main OS!
Apart from the DNS issue, I encountered another blocker: opening a port on Windows, so that Linux can connect to it. I need this to run the E2E tests, which are relying on Selenium to drive Chrome.
Linux is running under an Hyper-V VM, connected through a virtual network. On Windows, the firewall is enabled and for some reasons, it’s not trusting the virtual network and the port is closed.
So the solution is reverse tunneling! The first thing you’ve to do is install the SSH daemon and configure it with basic password authentication. Then feel free to use the following PowerShell snippet to automagically find the WSL2 address and redirect port. That’s it!
$port = 4444
$wslName = "Debian"
$wslUser = "luca"
$wslGetIpExpression = "$($wslName) run ""ip addr show eth0 | grep -Po 'inet \K[\d.]+'"""
$wslIp = (Invoke-Expression $wslGetIpExpression)
$redirectExpression = "ssh -R $($port):localhost:$($port) -N $wslUser@$wslIp"
Invoke-Expression $redirectExpression