Laradock Laravel database connection refused

Laradock is a PHP development environment which runs on Docker. It is a collection of images such as Nginx, Apache, MySQL, Composer, Supervisord, Redis, etc. that required for your application development. Starting with Laradock is pretty easy with the following command:

sudo docker-compose up -d nginx mysql phpmyadmin redis workspace

The above command will run all these images separated and automatically connect to your workspace environment. But in some cases connecting with the database will create the error with php artisan migrate command.

SQLSTATE[HY000] [2002] Connection refused

That is because we have the following settings in the .env file to connect with the database.

.....

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

.....

To connect your application with MySQL through Laradock, we have to set the DB_HOST=mysql instead of DB_HOST=127.0.0.1

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=laraqueue
DB_USERNAME=root
DB_PASSWORD=root

But sometimes not only this works for the MySQL connection. Go to the laradock directory and find my.cnf file under the mysql directory and add the default_authentication_plugin=mysql_native_password and the file should look like the below.

[mysqld]
sql-mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
character-set-server=utf8
default_authentication_plugin=mysql_native_password

Once you added this to your file you have to rebuild the mysql image with docker-compose build mysql and again start the service. If it’s still not connecting to the Laravel, then access the mysql terminal and the following changes.

sudo docker exec -it <mysql_container_id> bash
mysql -u root -p
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'default'@'%' IDENTIFIED WITH mysql_native_password BY 'secret';

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.