Reputation: 171
I have a mySQL server setup on my Windows machine, i also have WSL installed so i can use all the goodies of linux on my Windows machine. I have an assignment to make a JS api with express with a connection to a database, so i run my mySQL server everything is running correctly , but when i start the JS api using node index.js
from WSL and try to connect to the database, it throws an sql error
Server running on port 8080 , http://localhost:8080
/mnt/c/Users/ngkil/Documents/VSCode/WebDevAssignment2022/Backend/index.js:43
if (err) { throw err; }
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1195:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
Node.js v18.1.0
if i run the same command node index.js
from CMD the api works fine
Server running on port 8080 , http://localhost:8080
Connected to database
I do not understand what is going wrong between my mySQL server and WSL, the only interaction that exists between the two is that i try to connect to localhost from WSL, is it a unix problem???
Upvotes: 4
Views: 5003
Reputation: 2684
I am using WSL2, which runs on a VM. When you run an application from WSL2, and we attend to connect to a SQL Server running on Windows (same machine), localhost from WSL will resolve to the Linux environment, not Windows. To find the Windows address (host environment), we need to find the default gateway from the WSL2 CLI:
ip route
default via 172.22.32.1 dev eth0 proto kernel
The default IP on the output is the gateway. This IP address should be used on the connection string, or host value, for the application. We could also test the connection using telnet as such, and the connection should not be refused.
telnet 172.22.32.1 1433
Upvotes: 0
Reputation: 583
That is not working, because WSL2 is running with a virtual network (vNIC) that is created by the Windows Virtual Machine Platform (a subset of Hyper-V). Inside WSL2, localhost is the address of the vNIC.
The simplest solution would be to get an ip address of your windows and connect to the database with this address instead of localhost.
Unfortunately the IP will change every time you run your linux. WSL stores your windows host IP in /etc/resolv.conf
file. So you can modify /etc/hosts
to map winhost
to the host IP dynamically. To achieve this add the following lines at the end of ~/.bashrc
file:
export winhost=$(cat /etc/resolv.conf | grep nameserver | awk '{ print $2 }')
if [ ! -n "$(grep -P "[[:space:]]winhost" /etc/hosts)" ]; then
printf "%s\t%s\n" "$winhost" "winhost" | sudo tee -a "/etc/hosts"
fi
then run:
source ~/.bashrc
Now instead of localhost
use winhost
. Please let me know if this has helped you
Upvotes: 15