Monday, May 11, 2026

Laravel MySQL Connection Crash on Shared Hosting: How to Fix “SQLSTATE[HY000] [2002] No Such File or Directory” Errors and Restore 10‑Second Response Times in cPanel PHP‑FPM Environments

Laravel MySQL Connection Crash on Shared Hosting: How to Fix “SQLSTATE[HY000] [2002] No Such File or Directory” Errors and Restore 10‑Second Response Times in cPanel PHP‑FPM Environments

You’ve just pushed a hotfix to production, the queue workers are humming, but suddenly every request hangs on SQLSTATE[HY000] [2002] No such file or directory. The clock ticks past ten seconds, your monitoring alarm blares, and you’re scrambling through cPanel logs while your users watch the white‑screen of death. Sound familiar? This article cuts through the noise, gives you a reproducible fix, and shows you how to tune a shared‑hosting or low‑cost VPS so Laravel + MySQL runs at lightning speed again.

Why This Matters

When a Laravel app can’t find the MySQL socket, the entire request stack collapses. In a shared‑hosting environment the problem is often hidden behind cPanel’s PHP‑FPM pool limits, wrong unix_socket paths, or a mis‑configured my.cnf. Leaving it unchecked means:

  • Lost revenue from time‑out pages.
  • Higher bounce rates that damage SEO.
  • Increased support tickets and developer burnout.
  • Potential security exposure if fallback connections fall back to 127.0.0.1 with weak credentials.

Common Causes

  • cPanel’s php-fpm pool uses a different PATH than the CLI, so mysqli.default_socket points to a non‑existent file.
  • Shared hosts often ship MySQL with /var/lib/mysql/mysql.sock while the default Laravel config expects /tmp/mysql.sock.
  • Improper open_basedir restrictions block socket access.
  • Out‑of‑date pdo_mysql extension after a Composer upgrade.
  • Heavy traffic hitting the default max_children limit of PHP‑FPM, causing processes to abort before the DB connection is even attempted.
INFO: The fix is usually a three‑step dance—adjust the MySQL socket path, patch the PHP‑FPM pool, and warm‑up the opcache/Redis cache. Each step is covered below with copy‑paste‑ready code.

Step‑By‑Step Fix Tutorial

1️⃣ Verify the MySQL Socket Location

Log into the SSH console (or use the “Terminal” button in cPanel) and run:

$ mysqladmin variables | grep socket

The output will look like socket = /var/lib/mysql/mysql.sock. Note that path.

2️⃣ Update Laravel’s .env and config/database.php

Switch the DB_HOST to 127.0.0.1 if you must use TCP, or point the socket explicitly.

# .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_db
DB_USERNAME=your_user
DB_PASSWORD=your_pass
# Or use a socket
DB_SOCKET=/var/lib/mysql/mysql.sock

And in config/database.php:

'mysql' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],

3️⃣ Patch PHP‑FPM Pool Settings (cPanel)

Navigate to Software → MultiPHP INI Editor and add the socket override:

mysqli.default_socket = /var/lib/mysql/mysql.sock
pdo_mysql.default_socket = /var/lib/mysql/mysql.sock

If you control the pool file (/opt/cpanel/ea-phpXX/root/etc/php-fpm.d/www.conf), increase pm.max_children and set listen.owner to your cPanel user to avoid permission blocks:

pm = dynamic
pm.max_children = 30
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
listen.owner = yourcpaneluser
listen.group = nobody
listen.mode = 0660
TIP: After editing, restart PHP‑FPM from WHM or run systemctl restart php-fpm (root) or use “Restart PHP-FPM” button in cPanel.

4️⃣ Warm‑up OpCache & Redis

Deploy a tiny Artisan command to prime the cache:

getPdo(); // forces DB connection
        Cache::put('warmup', now(), 60);
        $this->info('Warmup complete');
    }
}

Schedule it in app/Console/Kernel.php to run every minute during deployment.

VPS or Shared Hosting Optimization Tips

  • Use a dedicated MySQL socket. If you have a VPS, place the socket in /var/run/mysqld/mysqld.sock and give the web‑user read/write rights.
  • Enable MySQL query cache (or use Redis). Add query_cache_type=ON and query_cache_size=64M in my.cnf.
  • Limit PHP‑FPM to realistic concurrency. For 2 GB RAM, pm.max_children = 20 is a safe sweet spot.
  • Turn on OPCache. In /opt/cpanel/ea-php*/php.ini set opcache.enable=1 and opcache.memory_consumption=128.
  • Deploy Supervisor for queue workers. Example:
[program:laravel-queue]
process_name=%(program_name)s_%(process_num)02d
command=php /home/username/public_html/artisan queue:work redis --sleep=3 --tries=3
autostart=true
autorestart=true
numprocs=3
user=username
redirect_stderr=true
stdout_logfile=/home/username/logs/queue.log

Real World Production Example

Company Acme SaaS migrated from a $5 shared plan to a $20 VPS on Ubuntu 22.04. By applying the steps above they reduced average request time from 12.8 s to 0.97 s and eliminated the “No such file or directory” errors completely.

$ curl -w "\nTime: %{time_total}s\n" -o /dev/null https://acme.example.com/api/users
Time: 0.94s

Before vs After Results

Metric Before After
Avg. API response 12.8 s 0.97 s
SQLSTATE errors per day 73 0
CPU usage (PHP‑FPM) 85 % 32 %

Security Considerations

Never expose the MySQL socket to the public internet. Keep chmod 660 /var/lib/mysql/mysql.sock and ensure only www-data or your cPanel user can read it. Also, rotate DB_PASSWORD regularly and store it in .env with permissions 600. Use mysql_native_password only if caching_sha2_password causes compatibility issues.

WARNING: Changing pm.max_children without checking RAM can cause OOM kills. Monitor free -m after each tweak.

Bonus Performance Tips

  • Enable realpath_cache_size=4096k in php.ini to speed up autoload.
  • Switch Laravel’s queue driver to Redis (instead of database) for sub‑second job latency.
  • Deploy Cloudflare Page Rules to cache static API responses (edge caching).
  • Use php artisan config:cache and route:cache after every deploy.
  • Consider Docker with php-fpm + nginx images if you outgrow shared hosting.

FAQ

Q: I can’t edit www.conf because I’m on shared hosting.
A: Use the “MultiPHP INI Editor” in cPanel to set mysqli.default_socket and pdo_mysql.default_socket. That overrides the pool file for your account.
Q: Should I use TCP instead of a socket?
A: TCP adds a few milliseconds and requires the MySQL port to be open. Use the socket when both services run on the same node—it’s faster and avoids firewall rules.
Q: My app still times out after the fix.
A: Check pm.max_requests and increase max_execution_time in php.ini. Also verify that Redis is up ( redis-cli ping ).

Final Thoughts

Fixing the “SQLSTATE[HY000] [2002] No such file or directory” error isn’t just about a single line in .env. It’s a holistic review of how PHP‑FPM, MySQL sockets, and your hosting stack interact. By aligning the socket path, tuning PHP‑FPM pools, and leveraging Redis & OPCache you restore sub‑second response times, lower server load, and keep your users happy.

SUCCESS: Implement the steps above, redeploy, and watch your GET /api/ calls drop under 1 second. Your monitoring graphs will thank you.

Monetize Your Improved Stack

If you’re looking for a reliable, low‑cost host that respects PHP‑FPM limits, consider Hostinger’s cheap secure hosting. Their shared plans include a dedicated MySQL socket, built‑in Redis, and 24/7 support—perfect for the Laravel + WordPress combos discussed here.

No comments:

Post a Comment