'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:[1]

In addition to using the IP from /etc/resolv.conf, you also have to open the 1433 port in Windows Firewall.

New rule - Port - Next - Specific ports: 1433 - Next - Allow - Next - Next - Name "WSL2 sql"


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. To find your wsl host address type wsl hostname -I in windows cmd shell)

P.S. Also note that some VPN software might brake WSL2/Windows network connectivity too. Turn off your VPN.

Solution 2:[2]

Have you try looking on the IP on /etc/resolv.conf?

Try connecting using that one, example: sqlcmd -S 192.168.202.65 -U sa -P pass

This is because of this

Solution 3:[3]

Enabling the "Virtual Machine Monitoring" worked for me. These four firewall rules are located in the inbound list, names starting with "Virtual Machine Monitoring" for:

  • Echo Requests (ICMPv4/v6)
  • RPC
  • DCOM-In
  • NB-Session-In

They appear to be disabled by default and once I enabled them, I was able to ping the host as well connect to my host sql server service using the IP address from the WSL generated resolv.conf file --

cat /etc/resolv.conf
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 1xx.1xx.1xx.1xx

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 QiQe Garbi
Solution 3 RominNoodleSamurai