Laravel Sail Database Connection Refused Error

Viewed 13487

I have created a new laravel project in laravel 8. I have set up Sail installation correctly, everything working fine for database connection in local but when I try to connect my database using sail it gives me an error

SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = laravel8 and table_name = migrations and table_type = 'BASE TABLE')

I have already cleared my config and cache files.

7 Answers

if you want run mysql in different port for example 3307 like below

ports:
  - 3307:3306

you should add FORWARD_DB_PORT environment variable to .env file like this

DB_PORT=3306 // this is for container port
FORWARD_DB_PORT=3307 // this is for local port

On cmd just run this command

docker network inspect bridge

You will get response like (similar) this:

[
{
    "Name": "bridge",
    "Id": "695c284c7b184839edf97d48161922dfe6c4827d0db917c3278f5634af7e00e2",
    "Created": "2022-02-22T22:17:30.8583513Z",
    "Scope": "local",
    "Driver": "bridge",
    "EnableIPv6": false,
    "IPAM": {
        "Driver": "default",
        "Options": null,
        "Config": [
            {
                "Subnet": "172.17.0.0/16",
                "Gateway": "172.17.0.1"
            }
        ]
    },
    .....
}

]

Copy "Gateway" ip address and replace with DB_HOST value in .env file. It will work

Changing DB_USERNAME from sail to root worked for me. I guess sail did not have the required privileges.

DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=database
DB_USERNAME=root # changed from sail
DB_PASSWORD=password

I had this same issue after creating a second sail project in my docker. It wasn't (still isn't) accepting the sail username or password but I could go in with root which gave me the error you gave above. I went to the Desktop Docker app, clicked the running container, found the mysql portion and ran the CLI, typed mysql and then ran the query CREATE DATABASE yourdatabasename; migration ran perfectly fine.

Maybe you should match the environment variables of .env.testing, since, as willpercey-gb says, the sail:install command updates the environment variables of .env, but not of .env.testing.

First off stop all services using brew especially MySQL

brew services stop MySQL

in your docker-yaml file:

laravel.test
   ports:
     - '70:80'
mysql:
   ports:
     - '3456:3306'

Now run your sail artisan migrate command.

this should solve your problem.

Related