For Windows 11 users, running WSL2 Ubuntu 22.04.3, do the following to connect to SQL Server Express running on the host.
Make sure TCP/IP is enabled in the SQL Server Configuration Manager.
Setup the firewall on windows to allow inbound connections.
Named instances of sql server use dynamic ports on Database engine startup. For WSL2 to know what port the server is running on, you have to run the SQL Server Browser service. This can be done from the SQL Server configuration Manager.You also have to allow connections to sqlserv.exe by making a custom program rule in the firewall. Or,
If your sql server is using a static/fixed port, or Configure a fixed port yourself, you can make a rule for that specific port in the firewall. In this case, you don't need the SQL Server Browser.
Then, using sqlcmd, you command should look something like this
sqlcmd -C -S [default gateway ip]\\sqlexpress -U [username] -P [password]
Note: the double backslash is important
The -C flag is to avoid the following error
"Sqlcmd: Error: Microsoft ODBC Driver 18 for SQL Server : SSL Provider: [error:0A000086:SSL routines::certificate verify failed:self-signed certificate]."
You can find your default gateway from the /etc/resolv.conf file, or run a command like netstat -rn
on WSL2.
When using SQL authenctication, you should set the Server authentication mode to "SQL Server and Windows Authentication mode" in the Server properties.
New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow
– Jimmyjimsonweed