Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WSL2 use "localhost" to access Windows service

I'm using WSL2 on Windows 10.

My dev stack is using a local webserver (localwp or wamp) on the host OS. I use WSL2 as the main terminal (SSH, Git, SASS, automation tools, ...).

What I need is a way to connect to my host services (MySql) from the WSL2 system using a server name instead of a random IP address.

It is already possible for the Windows host to connect to WSL2 services with "localhost". Is there a solution to do it the other way?

like image 640
Tim Avatar asked Jan 08 '21 08:01

Tim


People also ask

How do I access Windows files from WSL2?

Applications running on Windows, WSL2 Linux, and Docker containers are always accessed from localhost or 127.0. 0.1 . Open http://localhost:8888/ in a browser to view files in that directory ( index. html is returned by default).

Is WSL localhost the same as Windows?

WSL shares the IP address of Windows, as it is running on Windows. As such you can access any ports on localhost e.g. if you had web content on port 1234 you could https://localhost:1234 into your Windows browser. For more information, see Accessing network applications.

Does localhost share WSL?

One feature of WSL is that it allows sharing IP address space for services listening to localhost. This means one can access servers running on WSL from Windows as if it were running on Windows. This lets us, for instance, access a Docker container listening to 0.0. 0.0:8000 on WSL from Windows using localhost:8000 .


1 Answers

You should use hostname.local to access Windows from WSL2 because that will use the correct IP. Note that hostname should be replaced with the result of the hostname command run in WSL2. You can check the IP by running ping $(hostname).local from WSL2.

You also need to add a firewall rule to allow traffic from WSL2 to Windows. In an elevated PowerShell prompt run this:

New-NetFirewallRule -DisplayName "WSL" -Direction Inbound  -InterfaceAlias "vEthernet (WSL)"  -Action Allow

The command above should allow you to access anything exposed by Windows from WSL, no matter what port, however bear in mind that any apps you've launched get an automated rule created for them when you first launch them, blocking access from public networks (this is when you get a prompt from Windows Firewall, asking whether the app should be allowed to accept connections from public networks).

If you don't explicitly allow, they will be blocked by default, which also blocks connections from WSL. So you might need to find that inbound rule, and change it from block to allow (or just delete it).

See info here:

https://github.com/microsoft/WSL/issues/4585#issuecomment-610061194

like image 53
Jonas Kello Avatar answered Sep 22 '22 17:09

Jonas Kello