sql-serverubuntuwindows-subsystem-for-linuxwsl-2

Connect to SQL Server running on Windows host from a WSL 2/Ubuntu sqlcmd


I have a host running Windows 10, WSL 2. My guest is Ubuntu.

I'm trying to use sqlcmd to connect to the SQL Server running on my host machine, but I'm not sure what IP to use in the connection?

I've exposed/enabled basically everything from the SQL Configuration Manager on the host Windows SQL Server, and am using commands like this to try to connect:

sqlcmd -S 127.0.0.1 -U sa -P pass

Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Login timeout expired.


Solution

    1. Make sure SQL Server TCP/IP is enabled (under "SQL Server Configuration Manager" under "protocols")
    2. In your connection string, use the IP address from cat /etc/resolv.conf
    3. open the 1433 port in Windows Firewall. Open 'Windows Defender Firewall with Advanced Security' - Right click on 'Inbound Rules'. Go to New rule - Port - Next - Specific ports: 1433 - Next - Allow - Next - Next - Name "WSL2 sql"
    4. Disconnect all VPN software in Windows (if any) - it might break WSL2/Windows network connectivity

    NOTE: You just opened the port to the entire world, so either enable-disable this rule only when needed, or limit this rule to your WSL2 IP address only (double click the rule - Scope - Remote IP ads - Add your WSL2 address mask, it's usually 172.*.*.*. To find your wsl host address type wsl hostname -I in windows cmd shell). Use mask, not the exact address, because the IP changes every time you reboot (?)