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=5000to 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 /fto disable the HNS port exclusion behavior as
netsh int ipv4 show excludedportrange protocol=tcpshowed a lot of excluded ports that were not attributed to anything else.
Hopefully things are stable from now on. If not, I’ll update this post with further info.