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

Viewed 4558

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.

3 Answers

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

  1. In your connection string, use the IP address from cat /etc/resolv.conf
  2. open the 1433 port in Windows Firewall. Go to New rule - Port - Next - Specific ports: 1433 - Next - Allow - Next - Next - Name "WSL2 sql"
  3. Disable VPN software in Windows (if any) - it might brake 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. To find your wsl host address type wsl hostname -I in windows cmd shell)

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
Related