การแก้ปัญหาเบื้องต้นในการขึ้น Project แล้วติด Error

The error “SQLSTATE[HY000] [2002] Connection refused” means Laravel cannot connect to your MySQL database. Here’s how to fix it:


1. Check Your .env File

Run:

nano /var/www/your-laravel-project/.env

Verify the database settings:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1  # or 'localhost'
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
  • If you’re using Docker, DB_HOST should be the MySQL container name.
  • If MySQL is on another server, use that server’s IP instead of 127.0.0.1.

Save (CTRL+X, then Y, then Enter).


2. Test MySQL Connection

Run:

mysql -u your_username -p -h 127.0.0.1 -P 3306
  • If it works, Laravel should connect too.
  • If it fails, try localhost instead of 127.0.0.1.

3. Restart MySQL & Laravel Services

sudo systemctl restart mysql
sudo systemctl restart nginx php8.2-fpm

Clear Laravel caches:

php artisan config:clear
php artisan cache:clear
php artisan config:cache

4. Check MySQL Status

sudo systemctl status mysql

If MySQL is not running, start it:

sudo systemctl start mysql

5. Check MySQL Bind Address

If MySQL is listening only on localhost, update the MySQL config:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Find:

bind-address = 127.0.0.1

Try changing it to:

bind-address = 0.0.0.0

Save and restart MySQL:

sudo systemctl restart mysql

6. Grant MySQL Permissions (If Needed)

Run:

sudo mysql -u root -p

Then, execute:

GRANT ALL PRIVILEGES ON your_database.* TO 'your_username'@'%' IDENTIFIED BY 'your_password';
FLUSH PRIVILEGES;
EXIT;

7. Check If MySQL Is Using a Socket Connection

If you see an error “Can’t connect to local MySQL server through socket”, check:

sudo ls /var/run/mysqld/mysqld.sock

If the file is missing, restart MySQL:

sudo systemctl restart mysql

8. Use mysql_native_password (For MySQL 8+)

If using MySQL 8, try:

ALTER USER 'your_username'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_password';
FLUSH PRIVILEGES;

9. Restart Laravel Queue & Supervisor (If Using Queues)

sudo supervisorctl restart all

Try Again!

Now, reload your Laravel app. If the issue persists, let me know what error you get next! 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *