Skip to content

[WSL 2] WSL 2 cannot access windows service via localhost:port #4619

Closed

Description

Is your feature request related to a problem? Please describe.
although now windows can access wsl service with localhost:port via "localhostForwarding", but wsl cannot access windows service via localhost:port, please fix it, Thank you.

Describe the solution you'd like
When WSL 2 try to connect to localhost:port and be refused, try to connect to windows again.

Activity

  1. changed the title [-][WSL 2] WSL 2 cannot access windows service with localhost:port[/-] [+][WSL 2] WSL 2 cannot access windows service via localhost:port[/+] on Oct 25, 2019
  2. added
    wsl2
    on Dec 9, 2019
  3. numeric-lee commented on Jan 20, 2020

    @numeric-lee

    I was able to use graphic applications in WSL using XMING and Export DISPLAY=:0.0

    However, once I upgraded to WSL2 and switching to Export DISPLAY = 172.28.801:0 (my host#) it failed to connect

    Things tried:

    downloading VcXsrv
    switching to another graphics application
    running vcxsrv -ac from bash (command not recognized)
    running vcxsrv -ac from powershell (command not recognized)
    turning firewall off
    My Windows 10 build: 19041.1

    Here is a typical error message

    QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-lw' qt.qpa.screen: QXcbConnection:
    Authorization required, but no authorization protocol specified
    Could not connect to any X display.

    In #4106 you advise to run "vcxsrv -ac" from the bash command line and at least one user accepted that as a solution. I downloaded vcxsrv.exe from sourceforge as an .exe outside of bash, and I see no way to execute it from bash

    Many thanks

  4. gx761 commented on Feb 20, 2020

    @gx761

    is there any update?

  5. numeric-lee commented on Feb 20, 2020

    @numeric-lee
  6. fquinner commented on Feb 28, 2020

    @fquinner

    Numeric Lee (@numeric-lee) that's not really solved - that's a workaround. In WSL1 you could hit:

    localhost:port
    

    From the WSL environment and that would access the windows service directly without having to:

    • Script extraction of a magic IP address
    • Disable a firewall interface which freaks people (including me) out and doesn't persist on reboot

    Use cases are common including:

    • X11 Service running on windows host
    • Shared database access like postgres
    • Access docker on windows host from WSL client

    A different IP address, I could live with, though I would suggest that WSL should expose it via WSL_HOST or something like it does for WSL_DISTRO_NAME, but the firewall thing is a big pain point for me. There are a lot of quite similar issues but I'm hoping this is now the central one that will get done, ideally before this gets widespread release.

  7. Uzume commented on Feb 28, 2020

    @Uzume

    This is because despite the name (WSL=Windows Subsystem for Linux), WSL2 is not a Windows subsystem like WSL1 and Interix were. WSL2 is a lightweight Hyper-V-based virtual machine with its own separate network interfaces, IP addresses, etc. Localhost and 127.0.0.1 are host local references and having more than one host, they refer to different things in Windows host and Linux guest host.

    WSL2 already supplies some sort of special casing including accessing the Linux guest console/login for Windows terminal access to the Linux guest and means of accessing both the Windows host and Linux guest filesystems from both sides ("9p" Linux mounts vs. IFS redirector and UNC "\wsl$"). The best solution would be to generalize this to allow a configured list of port forwarding options. Then one could forward the server socket to the Linux guest allowing the guest to then believe and refer to the server as if it were local to the Linux guest host. For security and performance reasons, it would be good to use virtual machine specific socket system like that used by wslbridge2 (hvsocket).

    Another possibly simpler solution would be to come up with something that uses WSL_INTEROP sockets to create a generalized tunneling solution. I am not sure how stable they are though as they seem to depend on WSL sessions (perhaps a Windows service that opens a WSL session and sets up all the configured tunneling and then keeps the session open).

  8. andreialecu commented on Mar 10, 2020

    @andreialecu

    To anyone needing a workaround, run this on the Windows side:

    adb -a -P 5037 nodaemon server
    

    and this on WSL2:

    adb kill-server
    export ADB_SERVER_SOCKET=tcp:192.168.100.5:5037
    adb devices
    

    Replace the IP with your windows IP.

    Edit: I may have commented on the wrong issue. It was one on the same error but related to Android studio.

  9. raelmax commented on Mar 10, 2020

    @raelmax

    To workaround this on selenium+chromedriver, I´m running a socat on wsl2 relaying requests to localhost:port to windows-host:port. This workaround can be used in a lot of other cases. :)

  10. jordaofranca commented on Mar 16, 2020

    @jordaofranca

    Every time that I go back to wsl2 and give it a try, the same happens again. After updating windows, I'm not able to access localhost:port. Not event using wsl internal ip:port. Looks like it is a recurrent problem. Why we need to face it every update?

  11. Uzume commented on Mar 16, 2020

    @Uzume

    Andrei Alecu (@andreialecu) That only works for one particular service related to Android Debug Bridge.

    Rael Max (@raelmax) Yes, that is sort of what I suggesting by my comment about using WSL interop sockets. I had envisioned something with ncat (from nmap) but netcat and socat probably can also work. I thought about ncat because there should be both Windows and Linux versions available (sadly Windows Security identifies this as a "hacker tool" potential threat and quarantines it unless specifically allowed) so it was not too big of a stretch to just use pipes and depend on WSL interop to allow such to automatically cross the host-guest boundary.

    What commands are you using? How do you handle the Windows host side of things? Which Linux distribution are you using that has socat or did you compile that yourself? Providing the commands you are using would be helpful. Thank you.

    Jordão França Barroso (@jordaofranca) I believe WSL1 is still available in later versions of Windows 10 but you do need to set the WSL version for each distribution (and you can set the default version for new distributions too). Obviously moving back to WSL1 is also just a workaround and not a solution.

  12. raelmax commented on Mar 19, 2020

    @raelmax

    Uzume (@Uzume) I´m using Ubuntu 18.04 and I´ve installed socat via apt-get. :)

    My use case is as follow:

    • I need to use chromedriver(and chrome) running on Windows(host) and I need to control the chromedriver via selenium running on my Ubuntu(via wsl2).

    Since I can´t update my code to access chromedriver via an IP address, he always tries access chromedriver via the localhost. So to put chromedriver to run on localhost, I´m using the following command to relay requests from LOCALHOST:PORT to WINDOWSHOST:PORT.

    Command: socat -d -d TCP-LISTEN:9515,reuseaddr,fork TCP:$(cat /etc/resolv.conf | tail -n1 | cut -d " " -f 2):9516

    So each request that I did from my wsl2 machine to "localhost:9515" is relayed to "ipaddress:9516". On the windows side, I just need to open the 9516 port on my firewall.

    If I can help you with anything else, reach me out! :)

  13. Uzume commented on Mar 20, 2020

    @Uzume

    Rael Max (@raelmax) It seems you are not using WSL interop sockets at all and instead just using socat to forward Linux guest client (selenium) accesses to a localhost port to a Windows host IP and port (which also requires that the chromedriver server allows connections from IPs other than its own localhost).

    I imagine you could have just as easily used netcat or ncat (from nmap package). Thank you, I appreciate the feedback.

  14. gwd999 commented on Mar 29, 2020

    @gwd999

    still same issue as of end of March 2020 ... WSL2 [Ubuntu 18.04] on WINDOWS 10 Pro cannot access a defined DISPLAY (no matter how I define it if via localhost:0, or the WSL2 vEthernet adapter IPv4 address) on X-Server (neither Xming nor VcxSrv with and without -ac parameters) running on WINDOWS host system to display any graphic apps (eg xeyes or xclock).

  15. 116 remaining items

  16. tborrman commented on Jan 12, 2024

    @tborrman

    Craig Loewen (@craigloewen-msft)

    The .wslconfig edit to set networkingMode=mirrored is not working for me using Microsoft Windows [Version 10.0.22631.3007]
    I am trying to port forward Sublime with RemoteSubl using ssh -R 52698:localhost:52698 user@remote-server.
    I can see 127.0.0.1:52698 listening on the Windows side through powershell but looking for ports on the WSL Ubuntu terminal with netstat I don't see my port. What does networkingMode=mirrored do? How can I validate its working?

  17. deadcoder0904 commented on Feb 23, 2024

    @deadcoder0904

    Craig Loewen (@craigloewen-msft) Ari Mahpour (@amahpour) what is the minimal .wslconfig for using mirrored mode? i'm unable to access localhost:3000 for my next.js app. using wsl2 without docker-desktop. but docker run --rm -ti -p 80:80 nginx works fine & i can see nginx on localhost.

    is this config enough?

    .wslconfig

    [wsl2]
    localhostforwarding=true
    networkingMode=mirrored
    firewall=true
    

    do i have to restart my pc too? or is wsl --shutdown enough?

  18. amahpour commented on Feb 26, 2024

    @amahpour

    a2k (@deadcoder0904) Oddly enough I've got nothing configured except for systemd. What version of Windows and kernel version of WSL are you running?
    For windows type winver in the command shell
    For WSL go to a command shell and type in wsl --version

    Also, I presume your nginx test is Docker via the Windows command shell (not within a bash WSL 2 shell)?

  19. deadcoder0904 commented on Feb 26, 2024

    @deadcoder0904

    winver showed this:

    image

    wsl --version showed this:

    Kernel version: 5.15.133.1-1
    WSLg version: 1.0.59
    MSRDC version: 1.2.4677
    Direct3D version: 1.611.1-81528511
    DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
    Windows version: 10.0.22631.3155

    I presume your nginx test is Docker via the Windows command shell (not within a bash WSL 2 shell)?

    i'm using powershell 7. but i'm going into wsl by typing wsl on windows terminal (powershell 7) & then typing that docker run command. i'm using wsl2 without docker desktop bdw.

  20. amahpour commented on Feb 26, 2024

    @amahpour

    Yeah, you're certainly up to date. So with older versions of WSL 2 (or maybe it was WSL 1) you had to create tunnels or address the IP of the WSL instance (just like you would with a VM). Not sure when the switch happened but Microsoft now defaults WSL to NAT mode. This means that if you've got a a Node app running in WSL (i.e. the example you gave), addressing it via localhost on the Windows side should bring it up.

    Some follow up questions:

    • What distro are you using?
    • Did you install it via the Microsoft Store?
    • What happens when you remove all those config options in .wslconfig (and completely restart the computer)?
    • Are you 100% sure there's no firewall policy in your WSL distro?
    • Have you tried address your Node app using the IP of the WSL instance (instead of localhost) just like the old days with VMWare or VirtualBox?
  21. deadcoder0904 commented on Feb 26, 2024

    @deadcoder0904

    What distro are you using?

    Ubuntu.

    Did you install it via the Microsoft Store?

    I don't remember. But I think I did wsl --install

    What happens when you remove all those config options in .wslconfig (and completely restart the computer)?

    Haven't tried it yet.

    Are you 100% sure there's no firewall policy in your WSL distro?

    I am not sure. I did check & added or removed something in Firewall but don't remember what I did. Is there a way to reset it?

    Have you tried address your Node app using the IP of the WSL instance (instead of localhost) just like the old days with VMWare or VirtualBox?

    For some reason, my IP never worked. The one I got when I did ipconfig & at the end, there is a WSL IPv4 IP but yeah I couldn't ever get IP working when all answers on the internet say that it will work. It just never did for me.

    Bdw, I changed my Dockerfile to use ENV HOSTNAME '0.0.0.0' & it works for now but ENV HOSTNAME localhost doesn't.

    What's your suggestion? Do I try removing .wslconfig & restarting? Should I also reset firewall?

  22. amahpour commented on Feb 26, 2024

    @amahpour

    What version of Ubuntu?

    One sure bet way of doing it is install a new distro via the Microsoft Store (you can have many WSL distros at the same time just like your would VMs) and make sure there's no firewall set up. Make sure your .wslconfig is empty as well. Give that a shot and see what happens. I've done this countless times on new machines and, with the latest version of Windows 11 + WSL 2, it's always worked.

  23. amahpour commented on Feb 26, 2024

    @amahpour

    Regarding localhost versus 0.0.0.0 I can't really comment on how Windows handles all of that. To be honst I've completely forgotten. WSL matured to a point that I develop strictly in it now (versus in Windows, separate Linux machine, or VM)...

  24. deadcoder0904 commented on Feb 26, 2024

    @deadcoder0904

    What version of Ubuntu?

    I tried lsb_release -a & got this:

    No LSB modules are available.
    Distributor ID: Ubuntu
    Description:    Ubuntu 22.04.3 LTS
    Release:        22.04
    Codename:       jammy

    Alright, I'll try it again.

    Did you remove localhostforwarding too?

    I'm just unsure because I've only recently installed WSL because I wanted to try Docker & Docker doesn't work without WSL but yeah, still some weird errors.

  25. amahpour commented on Feb 26, 2024

    @amahpour

    I definitely do not have localhostforwarding set. I highly recommend removing it and/or starting from scratch like I proposed above.

    Regarding Docker: that's the beauty of Docker for Desktop. WSL 1 with Docker for Desktop was pretty lackluster but Microsoft did a phenomenal job integrating it with WSL 2. You just need to make sure you enable WSL 2 in the General settings and your distro (in this case Ubuntu 22.04) in Resources > WSL Integration.

    FYI, Docker for Desktop + WSL 2 is absolutely the way to go. If you're looking for alternatives (e.g. Docker CE within Linux or Rancher) it's not going to be as seamless.

  26. deadcoder0904 commented on Feb 28, 2024

    @deadcoder0904

    Ari Mahpour (@amahpour) so i removed everything in .wslconfig, restarted my pc & it works for now.

    the only thing i had to change is use 0.0.0.0 instead of localhost in dockerfile.

    for some reason, wsl2 without docker for desktop works much better for me. docker for desktop spins a lot of fans for no reason. it doesn't help i'm using a low-end pc for now. but for low-specs pc, wsl2 without docker desktop is the way.

    thanks for the help bdw.

    would love to know why localhost as hostname doesn't work? it should because all default templates use localhost. you can try one yourself by cloning a next.js example from https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile (i guess they are using 0.0.0.0 now but i still think its a bug in wsl2)

    you can see countless examples here (i'm assuming they are on linux/mac but their windows colleagues will face issues) -> https://sourcegraph.com/search?q=ENV+HOSTNAME+localhost+file%3Adockerfile&patternType=standard&sm=0

  27. the-moog commented on Mar 13, 2024

    @the-moog

    I've recently been experimenting with bridging in WSL2. I've tried this many times in the past and had limited and random success.
    I've recently worked out why this is and why there is so much said on the subject.

    ##Simply put
    The Win10/11 GUI leaves bits of config inside the hidden network layers, which break later invocations.

    ##Resolution
    However if you use PowerShell, (I know, sadly....), then you can make config that always works!!

    Note: I found I had to install some PowerShell helper modules and make sure I'm using an up to date version of PowerShell as it seems Win10 got left behind in that at some point.

    ##Root cause
    What is happening is that, e.g. you have an unused adapter interface on the host machine. When you try and re-configure networking in WSL2, if certain protocol extensions are installed in that adapeter - even if it is disabled and not attached - then WSL2 silently fails to configure the interface(s). If you look under the hood, the extension required on the various interfaces are missing. This explains the random things I've seen. And I found it by issuing the commands in the wrong order.
    But in PS I was able to see the obtuse messages that are being kept quiet. e.g. "A protocol on the network adapeter prevented it from binding to the virtual network." or "Ethernet Adapter XYZ is already bound to Microsoft Virtual Switch Protocol" or (and I laughed at this one) "ERROR: Failed whilemodifying virtual switch - Reason: Failed while modifying virtual switch settings" (lol)

    I find the old Control Panel Networking view is better than the newer Win10/11 in that you can see things sometimes don't look right... E.g. Things like Up thing being Down, TWO or ZERO copies of "vEthernet (WSL)" I've even seen them with - yep - The same UUID
    The properties should look something like this....

    I've not got time to document this properly and concisely, but I found the following commands (cut and paste from my notebook) provided the answers... Please, if you are curious enough and just as recless, and go and actually use them to screw your machine up. Don't say I did not warn you and tell you I take no responsibility for what happens.....

    ** BTW: Some of these won't work without local Administrator rights

    Get-NetAdapterBinding | where-object -property Description -like -value '*switch*' | format-table
    get-NetAdapter | where-object -Property Name -Like -value '*RJ45*' | get-NetAdapterBinding
    get-NetAdapter | where-object -Property Name -Like -value '*RJ45*' | get-NetAdapterBinding | Where-Object -Property ComponentID -eq -value 'vms_pp'
    get-NetAdapter | where-object -Property Name -Like -value '*RJ45*' | get-NetAdapterBinding | where-Object  -Property ComponentID -eq -value 'vms_pp'  | Set-NetAdapterBinding -Enabled $False
    # OK lets try changing something....
    get-NetAdapter | where-object -Property InterfaceDescription -Like -value '*Thun*' | select-object Name | Set-Variable -Value 'Thunderbolt'
    
    # Use Install-Module if the command you need are missing....
    Get-Module -All -ListAvailable | Where-Object -Property ModuleType -eq -Value 'Manifest'
    
    Install-Module # (...I did not write the rest of that down)
    help module
    
    Get-VMSwitch | Get-VMSwitchExtension | format-table
    Get-NetAdapter -IncludeHidden
    Get-VMSwitch | select-object -Property Name, Extensions | format-table
    Get-NetAdapterBinding
    Get-VMSwitchExtension
    Get-VMSwitchExtensionSwitchFeature
    help Enable-VMSwitchExtension -full
    Add-VMSwitchExtensionPortFeature
    hvc -v list
    hcsdiag list
    wsl --system
    Get-VM -ComputerName PC | Where-Object {$_.State -eq '*'}
    hcsdiag read -uvm 383890C3-1FEE-4E38-B328-B63A87D37A46 \etc\shadow     # Would have been rather jolly if that had worked... :|
    Get-NetAdapterAdvancedProperty
    Get-help Add-VMSwitchExtensionSwitchFeature -full
    # It seems wildcards work
    help get-vm*
    help vm

    With these I was able to see what was happening and clear out any cruft and create the correct switch bound to the correct adaprter with the correct name/settings etc.
    I also used the Virtual Switch manager from Hyper-V

    I also found that in .wslconfig you can write the following to bind WSL2 to a bridged network called 'Bridge'
    But then found you did not even need the actual bridge !!
    A VMSwitch alone is enough. I now have a VM (Centos) + WSL + Host all attached to the same LAN network right back over a VPN to the office....

    [wsl2]
    networkingMode = bridged
    vmSwitch = Bridge
    

    Next, see if I can use a bridge and some sort of VLAN or other multiplexing to get more than one adapter and more than one concurrent network.
    I think Open vSwitch may be useful...

  28. jasnei commented on Apr 19, 2024

    @jasnei

    Oh yes, I have the same issue, but after trying so many configurations from the issue or other issue. still not work.
    And I found out it's very easy to connect to windows service from WSL. you just change the IP address from 127.0.0.1 to your windows ip address, which works for me.

    from fastapi import FastAPI
    
    app = FastAPI()
    
    
    @app.get("/")
    async def root():
        return {"message": "Hello World"}
    
    if __name__ == "__main__":
        import uvicorn
        uvicorn.run(app, host="0.0.0.0", port=8010)

    This is a simple example. Then I run on window, normally, we will connect by 127.0.0.1:8010. This works when you were in your windows environment. But from WSL, it's not work. by changing the IP address to your_windows_ip:8010, then you should connect.

    ~$ curl 192.168.0.7:8010
    ~$ {"message":"Hello World"}
    

    192.168.0.7 is my windows IP, change to yours.

    Vice Verse

    If you start your service on WSL, you want to connect from windows, you will need the ip of your wsl

    ifconfig
    

    and your could check from PowerShell, well 172.26.43.102 is my WSL IP, you will need to change to yours.

    > curl 172.26.43.102:8010
    
    StatusCode        : 200
    StatusDescription : OK
    Content           : {"message":"Hello World"}
    RawContent        : HTTP/1.1 200 OK
                        Connection: keep-alive
                        Keep-Alive: timeout=4
                        Proxy-Connection: keep-alive
                        Content-Length: 25
                        Content-Type: application/json
                        Date: Fri, 19 Apr 2024 03:14:39 GMT
                        Server: uvicorn
                        ...
    Forms             : {}
    Headers           : {[Connection, keep-alive], [Keep-Alive, timeout=4], [Proxy-Connection, keep-alive], [Content-Length
                        , 25]...}
    Images            : {}
    InputFields       : {}
    Links             : {}
    ParsedHtml        : mshtml.HTMLDocumentClass
    RawContentLength  : 25
    

    It's working for me here, I hope this will help you too.

  29. benhillis commented on May 18, 2026

    @benhillis
    Member

    Accessing Windows services from WSL is supported via:

    1. Mirrored networking mode (recommended): set networkingMode=mirrored in .wslconfig. localhost inside WSL then maps to the same interfaces as the host, so a Windows service bound to localhost:PORT is reachable from WSL at the same address. Docs: https://learn.microsoft.com/windows/wsl/networking#mirrored-mode-networking
    2. NAT mode (default): use the Windows host IP, which is set as the nameserver in /etc/resolv.conf.

    Please reply if neither approach works for your scenario.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurewsl2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions