WSL Ubuntu中Ruby on Rails应用连接Windows本地PostgreSQL失败排查求助
Let’s break down your issue and walk through actionable fixes, then address the question about the missing WSL setup command.
Why Your Rails App Can’t Connect (But Windows psql Can)
The critical thing to understand is that localhost in WSL doesn’t map to your Windows machine’s localhost by default. Your Windows-based psql connects fine because it’s pointing to the local Windows PostgreSQL instance, but your Rails app (running in Ubuntu WSL) is trying to connect to its own localhost (the WSL environment), where no PostgreSQL is running. Here’s how to fix this:
1. Use Your Windows Machine’s Local IP in database.yml
First, find your Windows local IP address:
- Open Windows PowerShell and run
ipconfig - Look for the IPv4 address under your active network adapter (e.g.,
192.168.0.105)
Update your /apps/appname/config/database.yml to use this IP instead of localhost:
development: adapter: postgresql encoding: unicode pool: 5 host: 192.168.0.105 # Replace with your Windows IPv4 port: 5432 database: xxx username: postgres password:
2. Allow WSL Connections in PostgreSQL’s Configuration
PostgreSQL on Windows might block incoming connections from WSL by default. To fix this:
- Locate your
pg_hba.conffile (usually inC:\Program Files\PostgreSQL\<your-version>\data\) - Add a line to allow connections from your WSL subnet. To find your WSL subnet, run
ifconfigin Ubuntu and look for theeth0adapter’s IP (it will likely be in the172.16.0.0/12range). Add this line:
(Adjusthost xxx postgres 172.16.0.0/12 scram-sha-256scram-sha-256tomd5if you’re using an older PostgreSQL version.) - Restart the PostgreSQL service on Windows: Search for "Services" in the Start menu, find PostgreSQL, right-click > Restart.
3. Test the Connection from WSL
Verify you can reach the Windows PostgreSQL from Ubuntu using netcat or telnet:
# Using netcat nc -zv 192.168.0.105 5432 # Or telnet telnet 192.168.0.105 5432
If this succeeds, your network setup is correct. Restart your Rails server and try accessing /sign_in again.
Does the Missing Enable-WindowsOptionalFeature Command Cause This Issue?
No, this isn’t the problem. That command is required to enable WSL on Windows, but when you install Ubuntu via the Microsoft Store, Windows automatically enables this feature if it wasn’t already active. You can confirm this by running the command again in PowerShell—it will either report that the feature is already enabled, or enable it (but this won’t resolve your connection issue).
Bonus: Simplify with host.docker.internal (WSL 2+)
If you’re using WSL 2, you can use the special hostname host.docker.internal which automatically resolves to your Windows host IP. Update your database.yml like this:
host: host.docker.internal
This eliminates the need to manually update the IP if your Windows machine’s local address changes.
内容的提问来源于stack exchange,提问作者Steve

