python-3.xwindowsvisual-studio-codewindows-subsystem-for-linuxwaitress

Unable to connect to local server on WSL2 from Windows host


I have a Python3 project using waitress to serve on localhost on WSL2/Ubuntu 20. I start the server from VSCode remote but I can't connect to it from a browser on Windows using address http://127.0.0.1:5998 or http://localhost:5998, getting unable to connect error. I couldn't find what's wrong with it and appreciate any help.

Python server:

@app.route('/')
def index():
    return 'Success'
...
if __name__ == '__main__':
    from waitress import serve
    process_count = multiprocessing.cpu_count()
    serve(app, host="0.0.0.0", port=5998, threads=process_count)

I see it listening on WSL:

> sudo lsof -i -P -n | grep LISTEN
python3 1263 xxx    8u  IPv4  39138      0t0  TCP *:5998 (LISTEN)

I also tried 127.0.0.1 as serve() ip instead of 0.0.0.0 but didn't help.

I have a rule in Windows firewall for it:

> Get-NetFirewallRule -DisplayName WSL

Name                  : {9c5c5f2b-a9c7-42b7-82ac-f0c2b1819103}
DisplayName           : WSL
Description           :
DisplayGroup          :
Group                 :
Enabled               : True
Profile               : Any
Platform              : {}
Direction             : Inbound
Action                : Allow
EdgeTraversalPolicy   : Block
LooseSourceMapping    : False
LocalOnlyMapping      : False
Owner                 :
PrimaryStatus         : OK
Status                : The rule was parsed successfully from the store. (65536)
EnforcementStatus     : NotApplicable
PolicyStoreSource     : PersistentStore
PolicyStoreSourceType : Local

I've checked ports in use on Windows using netstat -o and nothing seem to be using port 5998.


Solution

  • I've solved this problem adding port forwarding on Windows.

    Run this on WSL:

    ifconfig
    

    The inet IP on eth0 entry is your WSL IP.

    Run this command on Windows:

    netsh interface portproxy add v4tov4 listenport=<port> listenaddress=0.0.0.0 connectport=<port> connectaddress=<your WSL IP>
    

    After this I could connect using localhost:<port> or 127.0.0.1:<port> or <WSL IP>:<port> from browser on Windows.

    You can list current port proxies using netsh interface portproxy show all command.

    You may need to add a firewall rule for your port on Windows.

    More info: https://github.com/microsoft/WSL/issues/4150#issuecomment-927091364