WSL2, Hyper-V & Reserved Ports
Are you having problems with "port already in use" while running apps in WSL under Windows? Hyper-V might be the culprit. This post explains why, and gives a possible workaround.
Allegedly a botched Windows update resets the dynamic TCP port range in some cases. When this happens, Hyper-V ends up aggressively reserving it for its own Windows Container Host Networking Service (HNS). The end result for me? I’ve occasionally been unable to connect to my Angular app running on port 4200 within WSL2.
Today I remembered that Windows had some sort of port reservation/exclusion mechanism, so I dug up the relevant command and sure enough, Angular’s port 4200 had (presumably) been stolen by Hyper-V1.
> netsh int ipv4 show excludedportrange protocol=tcp Protocol tcp Port Exclusion Ranges Start Port End Port ---------- -------- 1583 1682 2480 2579 > 4192 4291 5357 5357 6045 6144 7003 7102 28385 28385 ... ...
The following steps fixed it for me:
- On my Windows host in PowerShell, I ran
netsh int ipv4 set dynamic tcp start=51001 num=5000
to reset the dynamic port range to an area which I knew none of my apps used. - I also ran
reg add HKLM\SYSTEM\CurrentControlSet\Services\hns\State /v EnableExcludedPortRange /d 0 /f
to disable the HNS port exclusion behavior asnetsh int ipv4 show excludedportrange protocol=tcp
showed a lot of excluded ports that were not attributed to anything else. - Reboot
Hopefully things are stable from now on. If not, I’ll update this post with further info.
Footnotes:
In case you’re wondering, Hyper-V is used by the new WSL2, since it runs as a lightweight “virtual machine” in the background. I couldn’t just switch it off—although you can also fix it that way if you don’t need WSL2.