Search code examples
node.jswindows-subsystem-for-linux

How can you make a node server running on WSL2 forward over LAN so that it can be accessed by a phone?


I've tried the following:

https://www.youtube.com/watch?v=yCK3easuYm4

https://medium.com/codemonday/access-wsl-localhost-from-lan-for-mobile-testing-8635697f008

https://superuser.com/questions/1679757/how-to-access-windows-localhost-from-wsl2

https://superuser.com/questions/1131874/how-to-access-localhost-of-linux-subsystem-from-windows

https://superuser.com/questions/1732399/cannot-communicate-with-windows-localhost-from-wsl2

https://superuser.com/questions/1594420/cant-access-127-0-0-180-outside-of-wsl2-ubuntu-20-04

https://www.reddit.com/r/vscode/comments/11bp9oo/how_do_i_access_live_server_from_phone_i_tried/

https://www.reddit.com/r/bashonubuntuonwindows/comments/m1eb49/cant_access_web_server_from_wsl2_on_my_home/

https://learn.microsoft.com/en-us/windows/wsl/networking#accessing-a-wsl-2-distribution-from-your-local-area-network-lan

They all share a common procedure:

  • Create firewall exceptions for relevant ports
  • in Admin PowerShell run: netsh interface portproxy add v4tov4 listenport=3001 listenaddress=0.0.0.0 connectport=3001 connectaddress=(wsl hostname -I)
  • Find windows IPv4 address in PowerShell with ipconfig
  • on mobile phone, connect to same wifi network
  • go to <windows_IPv4_address>:3001
  • For good measure, in the Node.js Express app, I run:
server.listen(PORT, '0.0.0.0', ()=> {
    console.log(`⚡️ listening on ${PORT}`);
})

What happens:

  • Accessing <windows_IPv4_address>:3001, localhost:3001, 0.0.0.0:3001 and 127.0.0.1 on my phone times out
  • Can only view as localhost on local computer, not 0.0.0.0 or 127.0.0.1 despite setting '0.0.0.0' as a parameter to server.listen

So these instructions don't work. I am wondering if the advice is maybe outdated, I am not sure what I'm missing. I wish to access wsl2 localhost from LAN to test on mobile. Thanks


Solution

  • After a long search for a solution on how to access local services running on a Windows host from WSL2, I found a straightforward and effective method I'd like to share with you.

    On Windows, navigate to C:\Users{YourUserName} and create a file named .wslconfig. Add the following lines to the file:

    [wsl2]
    networkingMode=mirrored
    

    It's as simple as that, and it works like a charm.