Laravel生产环境数据库连接报错SQLSTATE[HY000][2002]求助
Hey Diego, let's work through this connection error you're hitting. The "No such file or directory" message here is a bit misleading when connecting to a remote database—let's break down the most likely fixes step by step:
1. Stop Using Socket for Remote Connections (Critical!)
Socket files (/var/run/mysqld/mysqld.sock) are meant for local MySQL connections only. When you're connecting to a remote host (hXXmysqlXXX), Laravel should use TCP/IP instead. The problem might be that your DB_SOCKET setting is overriding the remote host configuration in production.
Update your .env file in production to remove or comment out the socket line entirely:
DB_CONNECTION=mysql DB_HOST=hXXmysqlXXX DB_PORT=3306 DB_DATABASE=XXX_test DB_USERNAME=XXX_bdd DB_PASSWORD=XXXX # DB_SOCKET=/var/run/mysqld/mysqld.sock # Comment this out for remote connections
2. Verify Remote Connection Access
Make sure your production server can actually reach the remote MySQL host:
- Test if the port is open using
telnetornc:telnet hXXmysqlXXX 3306 # Or use nc if telnet isn't installed nc -zv hXXmysqlXXX 3306 - Check if the remote MySQL server allows connections from your production server's IP address. Log into the remote MySQL instance and grant access:
GRANT ALL PRIVILEGES ON XXX_test.* TO 'XXX_bdd'@'your-production-server-ip' IDENTIFIED BY 'XXXX'; FLUSH PRIVILEGES;
3. Clear Laravel Configuration Cache
Production environments often cache config files, so your updated .env settings might not be taking effect. Run these commands to clear caches:
php artisan config:clear php artisan cache:clear php artisan route:clear # Optional, but helpful to rule out any cached routes
If you're using OPcache or another PHP caching extension, restart your web server (Apache/Nginx) and PHP-FPM to ensure old configs aren't stuck in cache.
4. Double-Check Socket Path (Only If You Must Use Local Socket)
If for some reason your "remote" host is actually a local service (like a container running on the same production server), verify the socket file exists and has correct permissions:
# Check if the socket file exists ls -l /var/run/mysqld/mysqld.sock # Ensure MySQL is running ps aux | grep mysqld
If the socket is missing, restart your MySQL service to regenerate it.
5. Test the Connection Directly
Rule out Laravel-specific issues by testing the connection with the mysql command line tool from your production server:
mysql -h hXXmysqlXXX -P 3306 -u XXX_bdd -p XXX_test
If this works, the problem is definitely in Laravel's config or cache. If it fails, focus on fixing the network/MySQL permission issues first.
内容的提问来源于stack exchange,提问作者diego

