First, I'm assuming this is a WSL2 instance, not WSL1.
WSL2 instances really do run in a VM. The "VirtualMachinePlatform" component is a subset of Hyper-V. The WSL2 instances are running NAT'd (not bridged) behind their own virtual NIC vEthernet (WSL)
.
localhost
to the WSL2 instance points to the virtual interface, not to the Windows host. On the flip side, Windows does attempt to detect ports bound inside a WSL2 instance and allow Windows applications (such as a web-browser) access to the services on those ports via localhost
. However, this seems to break down for some people every so often, requiring a wsl --shutdown
of the VM in order to restore the functionality.
So yes, you can access the Rails app (running in WSL) using your web browser (running in Windows) at localhost
. However, you can't access the Postgres server running in Windows from the Rails server running in WSL2 via localhost
.
Or at least you shouldn't. I'm surprised that the psql
command seems to be working. Is it that:
psql
is running under WSL? (shouldn't work via localhost
)
- Or perhaps you mean that you are running
psql
from PowerShell or cmd? That would of course work via localhost
- Or perhaps the
psql
command is in the Windows path that gets propagated to WSL? That would also allow it to work via localhost
.
But ultimately, what you should need for accessing the Windows Postgres server from within WSL is to simply use a Windows IP or address pointing to it. I've detailed some options in this answer a few days ago. But short answer:
- Use mDNS, the "
.local
" domain. If your hostname is stevesdesktop
, then try replacing localhost
in your database.yml
with stevesdesktop.local
.
- If that doesn't work, use the Windows IP directly.
- Or edit
/etc/hosts
with the IP and a name to assign.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…