Get err_connection_refused accessing django running on wsl2 from Windows but can curl from Windows terminal

ghz 1years ago ⋅ 1694 views

Question

I got the err_connection_refused when trying to accessing django running on wsl2 (http://localhost:8000) from Windows but when I use curl http://localhost:8000 from Windows terminal bash, it's working fine. I have tried to add a new firewall inbound rule for port 8000 but it's still not working. Is there anything else I need to take care of.

django server
started

browser is not
working

curl directly not
working

bash curl is
working

Thanks a lot


Answer

Seems like a forwarding problem. WSL2's interface is NAT'd, whereas WSL1 was bridged by default. WSL seems to do some "auto-forwarding" of ports, but only on localhost. However, sometimes this auto-forwarding mechanism seems to "break down". The main culprit seems to be hibernation or Windows Fast Startup (which are both closely-related features).

  • Does the problem resolve if you do a wsl --shutdown and then restart the WSL2 session? If so, try disabling Windows' Fast Startup. I already had Fast Startup disabled due to a different (non-WSL issue) on my system, so that could be related to why I am not able to reproduce.

  • Along the same lines, do you Hibernate instead of powering off? In that case, a wsl --shutdown might resolve as well.

For future readers, note that the above two points seem to resolve the issue for most people who have upvoted and responded in the comments. However, if that does not work for you, the following were my original "additional suggestions":

  • For some additional ideas, see this github issue. There are some suggestions on services that might be needed. (Side question - Are you running Windows Home or Professional?)

  • Is there any chance that your Windows hosts file (e.g. c:\windows\system32\drivers\etc\hosts) points localhost to an IP other than 127.0.0.1? If I attempt to access via my local Windows IP address, rather than 127.0.0.1 or localhost, I get an ERR_CONNECTION_REFUSED as well.

  • Since you were looking at the firewall rules, maybe look at a forwarding rule instead of just an inbound allow?

  • If all else fails, try exporting/backing up the WSL2 session (see wsl --export), then import it in as a new WSL1 session. See if it works there.

On my WSL2/Ubuntu 20.04 system, I attempted to reproduce (but haven't been able to yet) with the following steps:

mkdir -p ~/src/dj-test
cd ~/src/dj-test
python3 -m venv dj
source dj/bin/activate
pip install Django
django-admin startproject config .
python manage.py runserver

(although I used activate.fish since I'm running the fish shell)

From Vivaldi web browser in Windows, accessed localhost:8000, which returned "The install worked successfully! Congratulations! ..."

curl under Powershell Core worked as well.