I know how to remap ports on the host ... [but] the Windows11 host assigns a different IP address to WSL2 every time I [restart WSL] so I cannot establish some kind of permanent rule.
Is there any solution to such a problem?
Quite a few possibilities, actually:
WSL1
If your services run under WSL1, then you can convert your distribution (or create a new one) and simply access the services using the Windows host IP. This used to be the preferred solution for most people, but WSL1 is starting to show its age a bit.
SSH reverse tunnels
As you've noticed, the fact that the IP address is dynamic makes port forwarding rules more challenging. Because of this, one solution is to reverse the "source" of the port forwarding so that it originates from within WSL2 (which always knows its own IP address). I go into detail on this in this Ask Ubuntu answer.
It does require that you run the ssh
command each time you restart WSL, but you can do this as part of the same script that brings up your service in the first place. For instance, place it in /etc/wsl.conf
in the [boot]
section as part of the command =
string.
WSL 1.1.0 or later
While not guaranteed, the latest WSL2 pre-release that dropped recently includes the following feature in the release notes:
Attempt to always reuse the same IP address in the WSL NAT network
This means that, in theory, once you assign the port forwarding rules, the IP address would not change unless for some strange reason it (or the subnet) was already in use.
As it is currently a pre-release, 1.1.0 has to be downloaded and installed manually through an Admin PowerShell with Add-AppxPackage <packagename>
, but the WSL team usually releases a production version after squashing any pre-release issues, so keep an eye on the releases page for a "Latest" with a version number greater than 1.1.0. When that happens, it should be available in and installable from the normal Microsoft Store page.
(Experimental) Bridge Network
Can I tell Windows to assign a static IP to WSL2?
Probably? I (still) haven't tried it myself as Microsoft seems to have kept this feature in the "Experimental" category for the last year, but as noted in the same AU answer from above, there is (was?) a feature in WSL2 which allows you to create your own Hyper-V network switch and specify it for use with WSL2. This blog post remains the best description of the feature I've seen.
There just hasn't been any mention on the part of Microsoft about this feature in the last year or so, so I'm not sure what the plans are for it, or whether it even is still enabled in the latest releases.