π Connecting to WSL2 server via local network
β Are you unable to connect to your WSL server from another computer or your mobile device on the same network?
(Running my local server in WSL2 with Next.js/CRA and being unable to access it from other devices on the local network.)
β Follow the steps below and you should be able to access the WSL2 server through other devices on the same local network.
βΆ Step 1
On the Windows PowerShell or cmd, use the command ipconfig
, and search for IPv4 Address to find your Windows IP address.
βΆ Step 2
Open the port on your machine in order to access it over your network. Run the command bellow in Windows PowerShell as admin:
netsh advfirewall firewall add rule name="Allowing LAN connections" dir=in action=allow protocol=TCP localport=3000
In my case, the port that I allowed is 3000.
(Change according to the port you want to allow -> localport=PORT_TO_ALLOW
)
βΆ Step 3
Still in Windows PowerShell, pass the port that the app is listening on to the corresponding port within WSL. Follow the command below to do this:
netsh interface portproxy add v4tov4 listenport=3000 listenaddress=YOUR_IPV4_ADDRESS connectport=3000 connectaddress=$($(wsl hostname -I).Trim());
-
listenport
: The port that Windows will listen to. -
listenaddress
: The address that your Windows will listen to (finded on step 1). -
connectport
: The port that your Linux distribution through WSL2 will listen to. -
connectaddress
: The public IP of your Linux WSL2 instance.
π (Note that the Hyper-V IP changes every time Windows reboots, so the public IP in WSL2 also changes). To avoid hardcoding due to updating the WSL IP every reboot, pass the $($(wsl hostname -I).Trim())
to dynamically put the IP of the WSL.
π₯ Finally, to see if everything is working properly, write the command:
netsh inteface portproxy show v4t0v4
If everything is fine, you should see something like:
Now, you can access your server using WINDOWS_IP:PORT_ALLOWED
π€ In my case, 192.168.18.217:3000
.
ππ
Top comments (0)