windowsapachesymfonylocalhostwsl-2

Localhost refused to connect on WSL2 when accessed via https://localhost:8000/ but works when using internal WSL IP adress


What I'm Trying to Achieve

To access localhost from my local machine during the development of a Symfony web app.

My Environment
Steps I've Taken
#!/bin/sh
REMOTEIP=`cat /etc/resolv.conf | grep nameserver | sed 's/nameserver\s//'` 
sed -i -E "s/client_host=[0-9\.]+/client_host=$REMOTEIP/g" /etc/php/7.4/mods-available/xdebug.ini
service php7.4-fpm start
service apache2 start
service mysql start  
What I Expect to Happen
What Actually Happens
What I've Tried
Conclusion

The behaviour is odd as it works sometimes but other times it doesn't when the exact same steps are carried out. I am unsure where else to look for answers and I can't seem to find anything online with this same problem. Please let me know if any config files, etc would be helpful. Thank you so much for your help! :)


Solution

  • When it's working normally, as you are clearly aware, the "localhost forwarding" feature of WSL2 means that you can access services running inside WSL2 using the "localhost" address of the Windows host.

    Sometimes, however, that feature breaks down. This is known to happen when you either:

    Typically the best solution is to disable Hibernation and Fast Startup. However, if you do need these features, you can reset the WSL localhost feature by:

    It's my experience that localhost forwarding will work after that. However, if it doesn't, thanks to @lwohlhart in the comments for mentioning that another thing to try is disabling IPv6 on WSL2, since (I believe) there's a possibility that the application is listening on IPv6 while the Windows->WSL2 connection localhost connection is being attempted on IPv6.

    You can disable IPv6 on WSL2 per this Github comment by creating or editing .wslconfig in your Windows user profile directory with the following:

    [wsl2]
    kernelCommandLine=ipv6.disable=1
    

    A wsl --shutdown and restart will be necessary to complete the changes.

    If you find that this works, it may be possible to solve the issue by making sure to either use the IPv4 (127.0.0.1) or IPv6 (::1) address specifically in place of localhost on the Windows side, or by configuring the service to listen on both addresses.