2002 🐬 MySQL

MySQL ERROR 2002 (HY000): Can't connect to local MySQL server through socket

The client couldn’t reach the MySQL server — it isn’t running, or the client is looking for the socket/port in the wrong place.

Seen on: MySQL Linux PHP Docker

Meaning

With localhost, MySQL clients use a Unix socket file (e.g. /var/run/mysqld/mysqld.sock). If the server is down or the socket lives elsewhere, you get 2002. PDO shows it as SQLSTATE[HY000] [2002] No such file or directory or Connection refused.

Common causes

  • MySQL service stopped or crashed
  • Socket path differs between client and server
  • localhost used in Docker where the DB is another container
  • Server listening only on a different port/interface
  • Disk full preventing startup

⚡ Quick fix

  1. sudo systemctl status mysql (or mariadb) and start it
  2. Use 127.0.0.1 to force TCP, or set the correct socket path
  3. In Docker, use the DB service name as host
  4. Check the MySQL error log for startup failures

Detailed fix by platform

Linux

  1. Check service and socket:
    bash
    sudo systemctl status mysql
    sudo journalctl -u mysql -n 50
    mysql -h 127.0.0.1 -u root -p     # TCP instead of socket

PHP

  1. Set pdo_mysql.default_socket / mysqli.default_socket in php.ini, or use host=127.0.0.1 in the DSN.

Docker

  1. DB_HOST=db (service name), not localhost.

How to diagnose

  1. Service — Is mysqld running?
  2. Transport — Socket or TCP? Which path/port?
  3. Logs — Why did it stop?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.