This week, for ReAsOnS, I wanted to run a server on WSL 2 that was accessible from the internet. This was surprisingly involved and requires lots of hard-to-find tricks to forward ports through 4 different layers of network abstractions and firewalls.
- In WSL, make sure your server is using IPv4. I spent a hell of a long time just trying to figure out why I couldn’t access the server from localhost. I had successfully run a handful of local http servers from WSL that were accessible from the Windows host, so I wasn’t sure what the problem was. It turns out this server, written in Java, wouldn’t work until I added
javaoptions. It appears that Java was defaulting to IPv6, and WSL doesn’t forward IPv6 properly, or something.
- In WSL, make sure you allow the port through your WSL firewall, if you’re using one. Using a WSL firewall might be redundant, but you might be using one. I usually use
ufwin my linux machines, so run I’d run
ufw allow $PORTin WSL.
- In Windows, forward your port from the public IP port to the WSL port using
netsh interface portproxy add v4tov4 listenport=$PORT listenaddress=0.0.0.0 connectport=$PORT connectaddress=127.0.0.1in a Powershell with admin rights. This is one of the hard-to-find but necessary WSL specific bits. It look like Windows creates a virtual adapter that isn’t properly bridged with your internet network adapter. I tried playing various bridging tricks, but in the end, I had to manually create a
portproxyrule using Windows’ network shell
netsh. This listens on all addresses and forwards the connection to the
localhost, which seems to be automatically bridged with WSL. You can also try to manually forward it to the WSL adapter. Use
ipconfigto find it. However, the WSL IP changes from time to time, so I recommend using local host instead. It might also be wise to listen explicitly on your internet facing IP instead of
0.0.0.0, but this seemed to work.
- In Windows, allow the port through the Windows firewall explicitly by adding a new
Inbound Ruleusing the
Windows Defender Firewall with Advanced Securityadministrative tool. This is accessible as
cmdand Powershell. Select
Inbound Rule, and click
New rule...in the action menu to the right, and work your way through the menu to allow the port explicitly. Normally, Windows asks if you want to allow applications through the firewall. This doesn’t seem to happen with WSL servers, so we have to manually add a rule.
- In your router, setup port forwarding for the port.