Search code examples
mysqlnode.jswindows-subsystem-for-linux

Can't connect to mySQL server from wsl


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???


Solution

  • 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