Oscar Fuentes
Oscar Fuentes

Reputation: 33

Attempt on Laravel/MySQLconnection with WSL and XAMPP

First I will explain my setup: I run Laravel in WSL (Windows Subsystem for Linux) and I have XAMPP on Windows. What I'm trying to do is to run MySQL service on XAMPP and connect it with my Laravel project. I have modified my .env file setting the root password and I have created the "laravel" database with phpMyAdmin.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=mypassword

With this setup I tried to run in WSL

php artisan migrate

But I got this error

SQLSTATE[HY000] [2002] Connection refused

Then I changed the DB_HOST to localhost, that is a common solution for this, but then I got this other error.

SQLSTATE[HY000] [2002] No such file or directory

Now I have no idea what else to do. I got stucked. Any help would be appreciated.

Upvotes: 1

Views: 3546

Answers (2)

Zep
Zep

Reputation: 1576

After a lot of digging, I found a solution. First, WSL cannot use localhost to communicate with XAMMP, but it should use $(hostname).local. You can test it by typing ping $(hostname).local in the WSL terminal: the keyword will be replaced by the host name and IP.

Second point, the app will be connecting from a "foreign" address, not localhost. Therefore, go to your phpMyAdmin interface, select the MySQL user that Flask is using, go to "Login information" and select "Any Host: %" in the "Host" section. I found a guide here. Note that now this user can be accessed by your network, so maybe choose a secure password.

More specifically, I had a similar problem with a python Flask app running in WSL, with XAMPP running in Windows. In the app, I had to change my SQLALCHEMY_DATABASE_URI variable to account for the different localhost. The variable should look something like this:

export SQLALCHEMY_DATABASE_URI="mysql+pymysql://sql_user:sql_password@$(hostname).local/YOUR_DATABASE"

Edit 2024: I installed WSL 2 in a new machine and this doesn't work anymore. It works with @$(hostname) instead of @$(hostname).local. There are discussions about this issue here. I also installed libnss-mdns as per this comment, but I am not sure that this is necessary.

Upvotes: 1

Jim Dunn
Jim Dunn

Reputation: 216

It seems you are running MySQL via XAMPP, under Windows, not in Linux (Ubuntu?). You should be running MySQL in the WSL2.

See this--- WSL stack overflow issue

Upvotes: 1

Related Questions