WSL: WSL2 cannot connect to localhost when the service is running on Windows

Please fill out the below information:

  • Your Windows build number: (Type ver at a Windows Command Prompt) Microsoft Windows [Version 10.0.19041.264]

  • What you’re doing and what’s happening: (Copy&paste the full set of specific command-line steps necessary to reproduce the behavior, and their output. Include screenshots if that helps demonstrate the problem.) I am using an HTTP proxy (ShadowSocks) on windows which is listening on localhost port 1080. Then, I want the command in WSL2 to go through that proxy. image

  • What’s wrong / what should be happening instead: curl: (7) Failed to connect to 127.0.0.1 port 1080: Connection refused

  • Strace of the failing command, if applicable: (If some_command is failing, then run strace -o some_command.strace -f some_command some_args, and link the contents of some_command.strace in a gist here).

  • For WSL launch issues, please collect detailed logs.

In WSL1, all things are fine. In WSL2 I could connect to the HTTP proxy through my Windows IP. I believe it is caused by WSL2 running in a separate VM.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 146
  • Comments: 87

Most upvoted comments

This is so frustrating

This is just a nightmare when doing software development. Was expecting to work this just out of the box after all those years. Can’t believe it doesn’t. Non-Windows-Users laughing at me. Again. Great job.

you can access Windows port from WSL2 using your local IP like 192.168.31.66 instead of localhost, though is not elegant

Come on WSL2, 2 years already! Do something please!

Update since Major Version 2.0.9

For step 2, you can just do wsl --update only, no need to do the pre-release anymore.


Original

@obedm503 Thanks for pointing it out. Would have never known it was actually being addressed all this time.

Had to take a few steps to get it working on my local environment. Just thought I’d share. The changes are on a pre-release of WSL so it won’t be available through regular update paths.

  1. Update Windows to at least the October 10th build. See more info here: https://github.com/microsoft/WSL/issues/4619#issuecomment-1778054020
  2. Update your WSL to the latest pre-release by running this in CMD or Powershell wsl --update; wsl --update --pre-release. You can view the changes of the pre-release versions here: https://github.com/microsoft/WSL/releases
  3. Update (or create) your .wslconfig file which is located at %USERPROFILE% in explorer. Add the following:
    [wsl2]
    networkingMode=mirrored # add this line if file already exists
    
  4. (Optional) Shutdown and restart your WSL (after a few seconds) so that the config changes apply.

Since getting it enabled, I haven’t had a single issue with my localhost being inaccessible. I could safely enable IPV6 again too.

Side note, pre-release v2.0.5 https://github.com/microsoft/WSL/releases/tag/2.0.5 moved the networkingMode setting from [experimental] to [wsl2].

Hey! I was having the same issue and I finally fixed it.

wsl --shutdown on the PowerShell worked for me like a charm! (Make sure to have closed all your wsl terminals first)

Hope it helps!

May 2021 - we’re still here! Unexpected behavior of WSL2 networking after each restart of my PC. Everytime I have NEW network issues.

That’s terrible to pretend WSL2 is stable and recommend it as default! Without stable networking all the fancy features of WSL2 is totally useless!!! Microsoft, please put efforts on this. First things - first!

Microsoft never changes

Is there a reason why this hasn’t received more attention? This is really, really annoying.

@fatichar turn off your firewall , it cost me serveral hours to get it out . This is difinitely another big problem

It happens randomly. Usually wsl --shutdown and restart fix the issue. Very annoying, hope there can be a patch for this issue.

The application running on WSL2 was unable to access API running on windows host at localhost:5001

This worked for me.

  1. Run ipconfig on windows host terminal
  2. Get the IPV4 Address from Ethernet adapter vEthernet (WSL) - Eg - 172.22.176.1
  3. Replace localhost:5001 with 172.22.176.1:5001

Thanks to https://github.com/sakai135/wsl-vpnkit

Actually, what I am looking for is something even more about proxy between WSL2 and Windows. I am expecting similar experiences like WSL1, where WSL and Windows are using the same address (at least users should not be bothered if services on WSL and Windows are listening on different addresses) and follow the same firewall rules.

If the network is not unified, why not use VM directly and using Samba to share the filesystem? WSL1 provide grate convenience compared with VM. 🤔

Am I too greedy? 😂

hi, the issue here is that while Windows can see the localhost ports of WSL, the inverse in not true by default. The ports forwarding are from WSL to Windows. If you do a netstat -an | grep 1080 on WSL, it should return nothing. However, when you pass it trough the Gateway (WSL switch), it will reach it.

Going forward, you can create a tunnel from Windows to WSL if you need/want to use localhost in your proxy (see: netsh interface portproxy command)

Hope this helps. WSL Corsair

@nunix can you give us an example? For example; I am trying to access 10134 port from WSL. 10134 port is on Windows assigned by Logitech Options application. I would like to access this port from inside WSL.

Is it possible to do with the portproxy? Currently my WSL IP is: 172.27.80.1

In my case, I am unable to connect to a service running on windows on ANY IP. Always the response is:

~/tcc/network-info$ telnet  172.17.0.1 5432
Trying 172.17.0.1...
telnet: Unable to connect to remote host: Connection refused

let’s wait for Build (and here I really am like you, I’m waiting on news) and see if something will done. @bplasmeijer I remember the SSH, actually right now, netsh is what I use for many of my demos.

still, I do agree with you that the “reverse forwarding” from Windows to WSL2 would be a great improvement

I also have experienced this issue when accessing my Windows’ Redis instance from my project running in WSL2. End up mapping Nameserver to localhost in /etc/hosts.

You can find Nameserver from /etc/resolv.conf, it looks like: nameserver 172.18.144.1 Then you can add line in /etc/hosts like: 172.18.144.1 localhost

Created a shell script to make life simpler: https://gist.github.com/toryano0820/6ee3bff2474cdf13e70d972da710996a

Not sure yet if there’s a downside with this method. But it works!

Thanks for the reply. I notice that many related issues are all about the network between the two systems. I can create a tunnel or proxy for this. But may I know if the WSL team has a specific plan or eta for the network improvement? Thanks.

hi, the issue here is that while Windows can see the localhost ports of WSL, the inverse in not true by default. The ports forwarding are from WSL to Windows. If you do a netstat -an | grep 1080 on WSL, it should return nothing. However, when you pass it trough the Gateway (WSL switch), it will reach it.

Going forward, you can create a tunnel from Windows to WSL if you need/want to use localhost in your proxy (see: netsh interface portproxy command)

Hope this helps. WSL Corsair

This behavior is insane and has one killer side effect: random and unpredictable service ports conflicts.

Let’s assume you have a windows process listening on 127.0.0.1 and for example port 9000

Port is visible from Windows

❯❯❯ NETSTAT.EXE -an | grep LISTEN | grep 9000
  TCP    0.0.0.0:9000           0.0.0.0:0              LISTENING
  TCP    127.0.0.1:9000         0.0.0.0:0              LISTENING
❯❯❯

but from WSL2 you are NOT seeing it:

❯❯❯ netstat -an | grep LISTEN | grep 9000
❯❯❯

Because you are not seeing it, then a wsl2 process can legitimately open the same port for listen, thinking that no other process is using it, like for example (note the absence of reuseaddr and reuseport)

❯❯❯ socat TCP4-LISTEN:9000,bind=127.0.0.1,fork exec:'/usr/bin/echo'

But this is now visible from both WSL2 and windows ! Two listeners on 127.0.0.1:9000

❯❯❯ NETSTAT.EXE -an | grep LISTEN | grep 9000
  TCP    0.0.0.0:9000           0.0.0.0:0              LISTENING
  TCP    127.0.0.1:9000         0.0.0.0:0              LISTENING
  TCP    127.0.0.1:9000         0.0.0.0:0              LISTENING
❯❯❯

And the WSL2 port can be randomly hit instead of the Windows one causing unpredictable behavior.

From my experience the Windows port seems to be ‘winning’ most of the time, but if the port is under heavy use it sometimes happen that the connection is accepted by the WSL2 listener.

Hey! J’avais le même problème et je l’ai finalement résolu.

wsl --shutdownsur le PowerShell a fonctionné pour moi comme un charme ! (Assurez-vous d’avoir fermé tous vos terminaux wsl au préalable)

J’espère que cela aide!

That works, but you need a shutdown/restart WSL2 after each launching Windows ? Someone knows why ?

This Microsoft page helped solve the problem on my end

https://docs.microsoft.com/en-us/windows/wsl/networking

Check in the “Accessing Windows networking apps from Linux (host IP)” section

Works pretty fine👌

@300LiterPropofol Me too!. After upgrading to win11, I found that WSL2 cannot connect to windows proxy even after using windows ip and closing firewall. Maybe a new bug of win11? Waiting for the fix.

Can confirm that WSL2 does NOT connect to Windows 10 services via ‘localhost’ hostname or IP addresses for the following version:

Microsoft Windows [Version 10.0.19042.1237]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Joe Gorse>ver

Microsoft Windows [Version 10.0.19042.1237]

I can confirm that migrating to WSL1 resolves the issue entirely. For a comparison of features, see https://docs.microsoft.com/en-us/windows/wsl/compare-versions

Notably, WSL1 outperforms WSL2 for Windows File access performance. While WSL2 has the “full Linux kernel”, it lacks serial device support that works for WSL1. See the link for full details.

The conversion command where “Ubuntu-20.04” may be any from the list wsl.exe -l -v:

wsl.exe --set-version Ubuntu-20.04 1

Cheers, Joe

When I upgraded my distro I started having all sorts of DNS problems (even with McAfee firewall turned off) and then today hit this issue of not being able to connect to a port of a process running in Windows from my Ubuntu command line.

I’ve reverted the distro to WSL 1: wsl.exe --set-version Ubuntu 1 and things seem to be back to normal now.

This happens very often on my end too (Windows 11 w/ WSL2). Running wsl --shutdown helps, but only for 15 minutes, until I get a new ERR_CONNECTION_REFUSED for localhost.

Any fix yet, other than reverting to WSL1?

None of the tricks shown here worked for me and I can’t switch the listening IP since it’s not my code. Rolling back to WSL1 worked, though. I just followed @jhgorse 's comment and ran on a powershell:

wsl.exe --set-version Ubuntu-20.04 1

Why is this taking so long, this can’t be that hard to fix, can it? It’s just annoying having to deal with stuff like this.

How is this still not resolved after all these people complaining of this issue for over a year? This is such a problem, my Linux coworkers keep telling me to drop WSL and just dual boot.

This is a complete duplicate of #4619, and all details there are applicable here. For those not wanting to scroll through everything there, there doesn’t seem to be any indication that WSL2 will go back to handling networking in a similar manner to WSL1. Your two options are 1: Put together some hacks and maybe it’ll work, or 2: Revert to WSL1 and hope WSL2 maybe someday changes its approach back to that of WSL1.

@obedm503 Thanks for pointing it out. Would have never known it was actually being addressed all this time.

Had to take a few steps to get it working on my local environment. Just thought I’d share. The changes are on a pre-release of WSL so it won’t be available through regular update paths.

1. Update Windows to at least the October 10th build. See more info here: [[WSL 2] WSL 2 cannot access windows service via localhost:port #4619 (comment)](https://github.com/microsoft/WSL/issues/4619#issuecomment-1778054020)

2. Update your WSL to the latest pre-release by running this in CMD or Powershell `wsl --update; wsl --update --pre-release`. You can view the changes of the pre-release versions here: https://github.com/microsoft/WSL/releases

3. Update (or create) your `.wslconfig` file which is located at `%USERPROFILE%` in explorer. Add the following:
   ```
   [wsl2]
   networkingMode=mirrored # add this line if file already exists
   ```

4. (Optional) Shutdown and restart your WSL (after a few seconds) so that the config changes apply.

Since getting it enabled, I haven’t had a single issue with my localhost being inaccessible. I could safely enable IPV6 again too.

Side note, pre-release v2.0.5 https://github.com/microsoft/WSL/releases/tag/2.0.5 moved the networkingMode setting from [experimental] to [wsl2].

This worked for me!

As a workaround, I added the following to my .zshenv file to set the IP address of the Windows host to an environment variable:

if [[ -n "$IS_WSL" || -n "$WSL_DISTRO_NAME" ]]; then
  if [[ -z "$WINDOWS_HOST_IP_ADDRESS" ]]; then
    export WINDOWS_HOST_IP_ADDRESS="$(powershell.exe -Command '(Get-NetIPConfiguration | Where-Object { $_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.Status -ne "Disconnected"}).IPv4Address.IPAddress' | tr -d '\r')"
  fi
fi

This way I can use the WINDOWS_HOST_IP_ADDRESS environment variable to proxy requests from WSL2 to the Windows host. For example, I run the Vite development server in WSL and proxy API requests to a .NET web application running on the Windows host.

I basically avoided this issue by using WSL1 for the past years, but I found a solution that works for me; If you don’t encounter this issue often just use $(hostname).local 😒

TLDR; This changes localhost to point to your Windows IP, 127.0.0.1 is still available for wsl. In windows you can access WSL via localhost as usual, because windows listens for exposed ports on WSL. Exposes your set windows port(s) via portproxies.

  1. Add this to your /etc/wsl.conf,
[boot]
command="sed -i \"s/127.0.0.1$(printf '\t')localhost/$(tail -1 /etc/resolv.conf | cut -d' ' -f2)$(printf '\t')localhost/g\" /etc/hosts 2>&1"

This command replaces the default localhost in /etc/hosts to point to your Windows IP, 127.0.0.1 is still available for wsl. This might require setting the host in your code to 127.0.0.1 for example in vite add server: { host: "127.0.0.1" } . Services running on Windows might need to be bind to 0.0.0.0 or it’s local ip to be accessible in WSL. From windows you can access WSL via localhost as usual, because windows listens for exposed ports on WSL.

  1. a. And use this powershell script to configure portproxies fix-wsl2-port-forwading-to-windows-localhost. The firewall rules, might not be necessary but can be helpful if you encounter issues.

    b. While the above script also helps you set the firewall rules. You can also execute the following command to set the portproxies manually in (admin) Powershell. In this example ports 8080,27017. (credits above)

$addr='0.0.0.0'; $ports=@(8080,27017); # set ports according to your use case, what ports from windows should be exposed.
$remoteport = (wsl hostname -I).Trim(); for( $i = 0; $i -lt $ports.length; $i++ ){ $port = $ports[$i]; echo "added portproxy ${addr}:${port} to ${remoteport}:${port}"; iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr"; iex "netsh interface portproxy add    v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport"; }

You can reset these proxies anytime using netsh interface portproxy reset

Because the WSL2 ip address changes every restart you need to add two scheduled tasks; 3. netsh with arguments interface portproxy reset to trigger ‘On an event’, Log ‘Security’ and Event ID ‘4647’ (log off). 4. The above powershell command, you can save it to a .ps1 file and execute with powershell with arguments c:\path_to_script.ps1 to trigger ‘At log on’ 5. You can test the automated scheduled tasks manually, by simulating a restart using wsl --shutdown you’ll see the ip has changed wsl.exe hostname -I.

This for me solves many of the main issues why I didn’t switch, it’s not the same as using WSL1. But does the job since you don’t have to change localhost host configurations for any of your projects. Which is frustrating when using WSL2. Bonus you can enjoy the latest features such as WSLg and better performance 😀.

This Microsoft page helped solve the problem on my end

https://docs.microsoft.com/en-us/windows/wsl/networking

Check in the “Accessing Windows networking apps from Linux (host IP)” section

Works pretty fine👌

Yes, this was already mentioned in this thread a few times (e.g. https://github.com/microsoft/WSL/issues/5211#issuecomment-706652801) Not a fix for the problem though, the issue is that one should be able to access it through localhost, not the IP.

I can confirm that migrating to WSL1 resolves the issue entirely. For a comparison of features, see https://docs.microsoft.com/en-us/windows/wsl/compare-versions

Notably, WSL1 outperforms WSL2 for Windows File access performance. While WSL2 has the “full Linux kernel”, it lacks serial device support that works for WSL1. See the link for full details.

The conversion command where “Ubuntu-20.04” may be any from the list wsl.exe -l -v:

wsl.exe --set-version Ubuntu-20.04 1

Inspired by the above solutions, I managed to make it work, though not perfectly.

Problem: My WSL2 cannot connect to the Socks 5 server running at 127.0.0.1:10809 on my Windows 10 host.

Solution:

  1. Change the socks 5 server setting - instead of listening to 127.0.0.1:10809, change it to listen to 0.0.0.0:10809
  2. Open Windows 10 firewall settings, and add an inbound rule that allows access to port 10809.
  3. Find out the WSL2 gateway address (for me it is 172.28.0.1)
  4. Now WSL2 can access the service using 172.28.0.1:10809

Note: none of the wsl --shutdown and netsh interface add tricks worked for me.

This was fixed in #4619

Did anyone got around “connection refused” issue even when using the nameserver ip?

I tried: disabled firewall, fast startup, allowed localhostForwarding, rebooted everything… Still can’t reach windows from WSL2 😦

cat /etc/resolv.conf
> nameserver 172.24.176.1

curl -XGET http://172.24.176.1:4040/inspect/http -I -v
*   Trying 172.24.176.1:4040...
* TCP_NODELAY set
* connect to 172.24.176.1 port 4040 failed: Connection refused
* Failed to connect to 172.24.176.1 port 4040: Connection refused
* Closing connection 0
curl: (7) Failed to connect to 172.24.176.1 port 4040: Connection refused
  1. In Powershell, use ipconfig command to find the IPV4 address in vEthernet (WSL).
  2. Add the normal proxy setting command in ~/.bashrc (e.g. export http_proxy=“http://172.65.25.3:1080”) for http & https using the address you found in the above step.
  3. source ~/.bashrc
  4. Close the current wsl terminal and open it again. curl www.google.com should work.

In the ssr software, use Socks5(support UDP) & Allow connections from LAN.

hi, the issue here is that while Windows can see the localhost ports of WSL, the inverse in not true by default. The ports forwarding are from WSL to Windows. If you do a netstat -an | grep 1080 on WSL, it should return nothing. However, when you pass it trough the Gateway (WSL switch), it will reach it. Going forward, you can create a tunnel from Windows to WSL if you need/want to use localhost in your proxy (see: netsh interface portproxy command) Hope this helps. WSL Corsair

@nunix can you give us an example? For example; I am trying to access 10134 port from WSL. 10134 port is on Windows assigned by Logitech Options application. I would like to access this port from inside WSL.

Is it possible to do with the portproxy? Currently my WSL IP is: 172.27.80.1

hi @gencer I would suppose it’s possible indeed, but on powershell if you do a netstat -an, on which interface is port 10134 mapped? if it’s localhost, then WSL2 cannot reach it indeed, if it’s bound to 0.0.0.0 then from WSL2 distro, try connecting to the <default gateway IP>:10134

Let me know the output of netstat and I will provide you the command

To simplify the issue, I will show the telnet result, 172.21.80.1 is the Windows IP on WSL switch. image

@dons20 cheers mate! For real, over a year of struggle

@dons20 Thanks! Works for me on W11.

This issue, WSL cannot connect to remote localhost, on my side had to do when the connected WiFi or LAN was set to “public network”. On “private network” everything was fine. With this fix WSL also connects to localhost while in public network. 😃

Awesome to hear! The release mentions it’s a window 11 fix. Anyone on Windows 10 to confirm it works for them as well?

That moment when you scroll the whole thread since 2020 hoping at this point someone would have a good fix but nope 😂😕

No joke. I’ve been following this thread since it was opened, hoping someone far more intelligent than me would have solved this by now. Yet here we are lol

None of the above solutions work for me. wsl --shutdown or change localhost in wsl to IP address or close firewall or add windows defender firewall inbound rule. My service is running on TCP 127.0.0.1:3000 0.0.0.0:0 LISTENING after doing netstat -an in powershell. Don’t know how to fix this still.

I also saw similar behavior. We are running Docker Desktop with WSL2 feature enabled. We created a container with 443 port exposed. And for some reason after 2 days of stable work the port become inaccessible. One more strange thing for me is that this port is inaccessible when I try to reach it from another host from the same network (https://host) or even from the same host via its IP (https://192.168.x.x), but it is accessible when I using localhost (https://localhost). Does anyone has any ideas what is happening?)