Old question that was bumped today via another answer, so I'll chime in. This question was originally asked for WSL1. While the "answer" is the same for WSL2, there are some slight differences that need to be addressed.
First, on WSL1, as the original accepted answer from 2016 mentions, the network is really running on the Windows host interface. That's why localhost
/127.0.0.1
(or the address of the Windows NIC) works there.
WSL2, on the other hand, runs virtualized, so the network interface is a vNIC with a different address than that of the Windows host. That network is actually NAT'd behind the Windows host. This is also why you can access a WSL1 instance using the Windows IP address from another machine on the network, but no so with WSL2.
But WSL2 does have a feature known as "localhost forwarding", which makes it work like WSL1 for localhost
/127.0.0.1
. This feature is turned on by default, but can be disabled (although I don't know of any reason for ever doing so, honestly).
This feature allows you to access a service (like a Rails app, in this question). If the port isn't in use on the Windows NIC, then WSL2 will auto-forward the localhost request to the same port on the WSL2 vNIC.
So all is well and good, and you can access both WSL1 and WSL2 services via localhost
, right?
Not so fast, unfortunately. Sometimes, as two other answers have mentioned, localhostForwarding
"breaks". We've identified two very common (and related) use-cases where this will happen:
- When the host Windows is hibernated.
- When the host Windows is powered on using Windows "Fast Startup" feature, which turns out to be enabled by default. This feature uses a form of hibernation.
The solution is:
- Don't hibernate if possible
- Turn off Fast Startup. You'll find it in the Control Panel. Navigate to Hardware and Sound -> Power Options -> Change what the Power Buttons do
- If you do find yourself in a situation where the feature is not working, as @AhmetK's answer mentioned, you can typically recover localhost forwarding by:
- Exiting all running WSL instances
- Issuing
wsl --shutdown
(from PowerShell, CMD, or even the Start Menu). While a full Windows restart will have the same effect, a wsl --shutdown
is much faster.
- Restart your WSL instance and running services/apps.
Reference the comments on this SO answer which have confirmed the issue and solution.