DEV Community

elizabeth
elizabeth

Posted on

Connect WSL2 to Windows PostgreSQL and SQL Server

To connect WSL2 to a Windows-hosted PostgreSQL or SQL Server instance, you need two things: a route from the Linux VM to Windows, and a database server that accepts connections from the WSL network. The first connection attempt often fails with connection refused or a timeout, and the cause is usually not the database itself. WSL2 runs Linux in a lightweight VM, so in the default NAT mode, localhost inside WSL points at Linux, not at Windows.

This guide shows how to prove the route before changing connection strings, choose a hostname strategy that survives restarts, and configure PostgreSQL, MySQL, and SQL Server to accept WSL clients. It also covers the Windows firewall rules and authentication settings that cause problems after routing is fixed.

Table of Contents

Why localhost fails in NAT mode

WSL2's default networking mode is NAT. The Linux distribution gets its own virtual Ethernet adapter and IP address, separate from the Windows host. Microsoft's guide to accessing network applications with WSL explains that a Linux program must use the Windows host's IP address to reach a server running on Windows. The reverse direction is different: Windows can usually reach a Linux server through localhost because WSL sets up localhost forwarding.

That forwarding is one-way. The localhostForwarding option binds WSL2's localhost to Windows localhost so Windows applications can reach Linux services; it does not make Linux localhost resolve to Windows.

Mirrored networking mode changes the picture. On Windows 11 22H2 and later, WSL can mirror the Windows network interfaces into Linux, and then Linux can reach Windows servers through 127.0.0.1. The rest of this guide covers both modes, because NAT remains the default and many existing setups still use it.

Step 1: Prove the route and port

Before editing postgresql.conf, pg_hba.conf, or a connection string, confirm that packets can reach the database port. In WSL, the Windows host address in NAT mode is the default gateway:

winhost_ip="$(ip route show default | awk '{print $3; exit}')"

if [ -z "$winhost_ip" ]; then
  echo "No default route found. Are you in mirrored mode?" >&2
  exit 1
fi

printf 'Windows host address: %s\n' "$winhost_ip"
Enter fullscreen mode Exit fullscreen mode

Now test TCP, replacing 5432 with 3306 for MySQL or 1433 for SQL Server:

if timeout 3 bash -c "</dev/tcp/$winhost_ip/5432" 2>/dev/null; then
  echo "TCP 5432 is reachable"
else
  echo "TCP 5432 is blocked or nothing is listening"
fi
Enter fullscreen mode Exit fullscreen mode

A failed test is useful information. It means you should fix routing, the listener, or the firewall before touching the client configuration.

It also helps to see what the database is actually listening on from Windows. In an elevated PowerShell window:

Get-NetTCPConnection -LocalPort 5432 -State Listen |
  Select-Object LocalAddress, LocalPort, OwningProcess
Enter fullscreen mode Exit fullscreen mode

If LocalAddress is 127.0.0.1 or ::1, the server is bound to loopback only and WSL cannot reach it in NAT mode. If it is 0.0.0.0 or ::, the server is listening on all interfaces, and the remaining problem is likely the Windows firewall or routing.

Step 2: Choose a hostname that survives restarts

The gateway address can change when the WSL virtual network is recreated, so hard-coding it into an ORM configuration or a committed .env file is fragile. There are three common ways to handle this, plus the mirrored-mode option.

Two WSL settings shape the choices below: generateHosts controls whether WSL rewrites /etc/hosts, and networkingMode selects NAT or mirrored networking. The WSL configuration reference documents both settings.

Runtime gateway IP

The most reliable NAT-mode approach is to resolve the Windows host address each time it is needed. Put a small helper on your PATH:

#!/usr/bin/env bash
# ~/.local/bin/winhost
set -euo pipefail
ip route show default | awk '{print $3; exit}'
Enter fullscreen mode Exit fullscreen mode

Make it executable and ensure ~/.local/bin is on your PATH:

chmod +x ~/.local/bin/winhost
export PATH="$HOME/.local/bin:$PATH"
Enter fullscreen mode Exit fullscreen mode

Then use it in client commands:

psql -h "$(winhost)" -p 5432 -U wsl_app -d appdb
mysql -h "$(winhost)" -P 3306 -u wsl_app -p appdb
sqlcmd -S "$(winhost),1433" -U wsl_app -P 'your-password' -d appdb -C
Enter fullscreen mode Exit fullscreen mode

This survives both WSL and Windows restarts because the address is looked up fresh. The trade-off is that every tool needs to call the helper, or you need to export the result into an environment variable when the shell starts.

The .local mDNS name

WSL's hostname defaults to the Windows computer name, so $(hostname).local is sometimes used as a hostname for the Windows machine. It relies on mDNS, the multicast DNS protocol that resolves .local names without a conventional DNS server.

Microsoft's WSL troubleshooting notes on resolving .local names explain the caveats. In NAT mode, .local resolution is not supported when DNS tunneling is enabled; you can disable DNS tunneling or switch to mirrored mode. In mirrored mode, Linux must be configured for mDNS by installing libnss-mdns and enabling mdns_minimal in the hosts line of /etc/nsswitch.conf.

Test it before relying on it:

getent hosts "$(hostname).local"
Enter fullscreen mode Exit fullscreen mode

If that returns the Windows host address, the name may work for your clients. If it returns nothing, or returns a different address, do not build your connection strings around it. The WSL hostname can also be changed, in which case $(hostname).local no longer matches the Windows computer name.

A static winhost entry

A common workaround is to add a winhost entry to /etc/hosts that points at the current gateway address:

printf '%s winhost\n' "$(ip route show default | awk '{print $3; exit}')" |
  sudo tee -a /etc/hosts
Enter fullscreen mode Exit fullscreen mode

Then test it with getent hosts winhost and use winhost as the database host. This makes connection strings shorter, but it is not truly static. Because generateHosts defaults to true, WSL generates /etc/hosts, and a hand-edited entry may not survive regeneration. Setting generateHosts=false lets you manage the file yourself, but then you also take responsibility for the rest of its contents. And even a preserved entry still points at an IP that can change when the WSL network is recreated.

Use this approach for a short-lived setup, or pair it with a script that rewrites the entry at boot. Do not treat it as a permanent fix.

Compare the options

Strategy Works in NAT mode Survives restarts Main caveat
Runtime gateway IP Yes Yes, if resolved at runtime Requires a helper or environment variable
$(hostname).local Only with DNS tunneling disabled Usually, if mDNS works Depends on mDNS, hostname, and libnss-mdns
Static winhost entry Yes Only if the entry is updated WSL may regenerate /etc/hosts; IP can change
127.0.0.1 in mirrored mode No, mirrored only Yes Requires Windows 11 22H2 or later

Mirrored mode: the simplest fix

If you are on Windows 11 22H2 or later, mirrored networking removes most of the address churn. Add this to %UserProfile%\.wslconfig:

[wsl2]
networkingMode=mirrored

# Optional: only if you need to reach Windows by one of its LAN IPs
[experimental]
hostAddressLoopback=true
Enter fullscreen mode Exit fullscreen mode

Then restart WSL from PowerShell:

wsl --shutdown
Enter fullscreen mode Exit fullscreen mode

Reopen your distribution and connect to 127.0.0.1. Microsoft's documentation notes that mirrored mode supports the IPv4 loopback address but not the IPv6 loopback address ::1, so prefer 127.0.0.1 over localhost in connection strings. hostAddressLoopback is only needed when you want to use an additional IP address assigned to the Windows host; it is not required for 127.0.0.1.

Mirrored mode also lets you keep PostgreSQL on 127.0.0.1 and MySQL on 127.0.0.1, avoiding a broader network exposure. If you want the full networking model, how WSL2 reaches the Windows host in NAT and mirrored modes explains why localhost behaves differently in each mode and when hostAddressLoopback is needed.

Step 3: Open the Windows firewall for the WSL adapter

In NAT mode, Windows Firewall may block the database port even after the server is listening. The WSL virtual adapter is often classified as a Public network, so a rule limited to Private profiles will not help.

First, confirm the adapter name. Start your WSL distribution so the adapter exists, then run PowerShell:

Get-NetAdapter | Where-Object Name -like "*WSL*" |
  Select-Object Name, InterfaceDescription, Status
Enter fullscreen mode Exit fullscreen mode

Create an inbound rule scoped to that adapter, not to every network:

New-NetFirewallRule -DisplayName "PostgreSQL from WSL2" `
  -Direction Inbound -Action Allow -Protocol TCP -LocalPort 5432 `
  -InterfaceAlias "vEthernet (WSL*)"
Enter fullscreen mode Exit fullscreen mode

Repeat the rule for 3306 (MySQL) or 1433 (SQL Server). The adapter may appear as vEthernet (WSL) or vEthernet (WSL (Hyper-V firewall)); the wildcard covers both. If your adapter has a different name, adjust the alias rather than removing the scope.

On Windows 11 22H2 and later with WSL 2.0.9 or newer, the Hyper-V firewall also filters WSL traffic. If a normal Windows firewall rule looks correct but traffic still disappears, check the Hyper-V firewall settings as well.

Step 4: Configure PostgreSQL

PostgreSQL has two relevant configuration files: postgresql.conf and pg_hba.conf. Both live in the data directory, which for the EDB Windows installer is usually under C:\Program Files\PostgreSQL\<version>\data. Edit them with administrator rights.

Set listen_addresses

PostgreSQL's documentation for listen_addresses confirms that the default is localhost, which accepts only loopback TCP connections. In NAT mode, change it to:

listen_addresses = '*'
Enter fullscreen mode Exit fullscreen mode

This makes PostgreSQL listen on all Windows interfaces. The firewall rule and pg_hba.conf still control who can actually connect. If you use mirrored mode, set listen_addresses = '127.0.0.1' and connect to 127.0.0.1; that avoids exposing the port to the LAN.

listen_addresses is read only at server start, so restart the PostgreSQL Windows service after changing it.

Add a pg_hba.conf rule

Add a rule for the WSL client:

# TYPE  DATABASE  USER  ADDRESS   METHOD
host    all       all   samenet   scram-sha-256
Enter fullscreen mode Exit fullscreen mode

The pg_hba.conf documentation explains that samenet matches any address in a subnet the server is directly connected to. That covers the WSL NAT subnet without hardcoding a CIDR that can change. If you prefer a tighter rule, use the WSL subnet explicitly, for example 172.30.96.0/20. Put the line before any catch-all reject; PostgreSQL uses the first matching record and does not fall through to later ones.

scram-sha-256 is the current password authentication method; md5 is deprecated. The role must have a password set:

CREATE ROLE wsl_app LOGIN PASSWORD 'use-a-strong-password';
GRANT CONNECT ON DATABASE appdb TO wsl_app;
Enter fullscreen mode Exit fullscreen mode

Apply and test

On Windows, PostgreSQL applies pg_hba.conf changes immediately to subsequent new connections, so a reload is not required for this file. You do need the service restart because listen_addresses changed.

Test with the real client:

psql -h "$(winhost)" -p 5432 -U wsl_app -d appdb
Enter fullscreen mode Exit fullscreen mode

If psql is not installed in WSL, install the PostgreSQL client package for your distribution. A successful TCP test followed by no pg_hba.conf entry means the route works but the client address does not match your rule.

Step 5: Configure MySQL and SQL Server

The same routing and firewall rules apply to MySQL and SQL Server, but each engine has its own bind and authentication settings.

MySQL

MySQL's troubleshooting guide for connection problems notes that a server started with bind_address=127.0.0.1 listens only on the loopback interface and does not accept remote connections. It also notes that skip_networking disables TCP entirely and that Windows Firewall can block port 3306.

Open the my.ini file used by the MySQL service. Under [mysqld], set:

[mysqld]
bind-address = 0.0.0.0
Enter fullscreen mode Exit fullscreen mode

Restart the MySQL service. If you use mirrored mode, leave bind-address = 127.0.0.1 and connect to 127.0.0.1 instead.

Also check that the MySQL account is allowed to connect from the WSL address. An account restricted to localhost will reject a TCP connection from the WSL subnet. Scope the account to the WSL subnet where possible, or use a wildcard and rely on the firewall to limit reachability.

Test it with:

mysql -h "$(winhost)" -P 3306 -u wsl_app -p appdb
Enter fullscreen mode Exit fullscreen mode

SQL Server

Microsoft's SQL Server lesson on connecting from another computer walks through enabling TCP/IP. Developer, Express, and Evaluation editions install with limited network connectivity, so TCP/IP may be disabled.

In SQL Server Configuration Manager, expand SQL Server Network Configuration, select Protocols for <instance>, right-click TCP/IP, and choose Enable. Restart the SQL Server service afterward.

A default instance listens on TCP 1433 once TCP/IP is enabled. Named instances, including SQL Server Express, use dynamic ports by default. Either configure a fixed port in the TCP/IP properties or keep SQL Server Browser running and open UDP 1434. Then open the chosen TCP port for the WSL adapter, as described in Step 3.

Authentication is the other common blocker. Microsoft's guide to SQL Server authentication modes explains that mixed mode enables both Windows Authentication and SQL Server Authentication. If the instance is Windows-only, a Linux client using a SQL login will fail.

In SQL Server Management Studio, right-click the server, open Properties > Security, select SQL Server and Windows Authentication mode, and restart SQL Server. If SQL Server Agent is running, restart it too. Create a dedicated SQL login and map it to a database user rather than enabling the well-known sa account for application connections.

Test with:

sqlcmd -S "$(winhost),1433" -U wsl_app -P 'use-a-strong-password' -d appdb -C
Enter fullscreen mode Exit fullscreen mode

For a named instance with a fixed port, replace 1433 with that port. The -C option trusts the server certificate, which is commonly needed for a local development instance with a self-signed certificate; do not use it for production. If your client supports the tcp: prefix, tcp:winhost,1433 forces TCP.

Step 6: Verify and centralize the hostname

A TCP handshake only proves that the port is reachable. Verify each database with the real client so that authentication, database selection, and driver behavior are also tested.

Centralize the hostname in one place instead of scattering IP addresses across tools. For NAT mode, keep using the winhost helper from Step 2:

export DB_HOST="$(winhost)"

psql -h "$DB_HOST" -p 5432 -U wsl_app -d appdb
mysql -h "$DB_HOST" -P 3306 -u wsl_app -p appdb
sqlcmd -S "$DB_HOST,1433" -U wsl_app -P 'your-password' -d appdb -C
Enter fullscreen mode Exit fullscreen mode

Build ORM connection URLs and migration-tool settings from DB_HOST at runtime. Avoid committing a gateway IP to .env, alembic.ini, flyway.conf, or any other configuration file that will outlive the current WSL session. In mirrored mode, set DB_HOST=127.0.0.1 and skip the helper.

Troubleshooting quick reference

Symptom What it usually means Fix
Connection refused The host was reached, but nothing is listening on that port or interface. Check Get-NetTCPConnection; fix listen_addresses or bind-address; confirm the port.
Connection times out A firewall or route is dropping packets. Check the scoped inbound rule and the Hyper-V firewall; retest with /dev/tcp.
no pg_hba.conf entry for host ... PostgreSQL rejected the client address before authentication. Add a samenet or WSL-subnet host line and open a new connection.
password authentication failed The role exists, but the password or authentication method is wrong. Reset the role password; use scram-sha-256.
MySQL Access denied for user ...@'172.x' The account is not granted for the WSL host. Create or grant an account for the WSL address or a suitable wildcard.
SQL Server Login failed TCP works, but the instance is Windows-only or the login is disabled. Enable mixed mode, create or enable a SQL login, and restart SQL Server.
Works until a reboot A hard-coded IP address went stale. Resolve the host at runtime or switch to mirrored mode.

Conclusion

Connecting WSL2 to a Windows-hosted database is usually a routing problem followed by a server-configuration problem. Prove the route and port first, then choose a hostname strategy that matches your networking mode. Mirrored mode with 127.0.0.1 is the cleanest option on Windows 11 22H2 or later; NAT mode needs a runtime gateway lookup or a carefully maintained hosts entry.

Once the route works, make each server accept the connection. PostgreSQL needs listen_addresses and a matching pg_hba.conf rule, MySQL needs a reachable bind-address and a suitable account, and SQL Server needs TCP/IP, mixed-mode authentication, and an open port. Scope the firewall to the WSL adapter, centralize the hostname in one helper, and restarts will stop turning a working connection into a stale-IP error.

Top comments (0)