> ## Content Index
> Fetch the complete content index at: https://www.ggorantala.dev/llms.txt
> Use this file to discover other available public pages before exploring further.

# ERROR 2002: Can't Connect to Local MySQL Server Through Socket
- URL: https://www.ggorantala.dev/mysql-error-2002-cant-connect-through-socket/
- Published: 2026-11-27T19:04:00.000Z
- Updated: 2026-11-30T19:05:15.000Z
- Description: ERROR 2002 means the MySQL client went looking for a Unix socket file and never reached a server. Here's how to tell a stopped server from a socket in the wrong place, read the number in brackets, and fix it for the CLI, PHP and Python.
- Author: Gopi Gorantala
- Tags: mysql-error-2002, unix-socket, localhost, mysql-connections, php, mysql, mysql-errors

I was sure the password was wrong. It wasn't. The client never got far enough to send one.

That's the whole trick with **ERROR 2002, "Can't connect to local MySQL server through socket"**. It looks like a login problem because it shows up the moment you try to log in. But no server ever saw your request. The MySQL client library raised it on its own, after it went looking for a file on disk and came back empty-handed.

## The message you're staring at

From the `mysql` command-line client it looks like this. The text below is the message format from the [MySQL 9.7 client error reference](https://dev.mysql.com/doc/mysql-errors/9.7/en/client-error-reference.html?ref=ggorantala.dev) (`CR_CONNECTION_ERROR`, "Can't connect to local MySQL server through socket '%s' (%d)") filled in with the Debian/Ubuntu default path. I couldn't install a MySQL server or the `mysql` CLI in my workspace this time, so this one's from the reference, not my terminal:

```log
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

```

The same wording turns up from anything built on libmysqlclient, like Python's `mysqlclient` (`MySQLdb.OperationalError: (2002, "Can't connect to local MySQL server through socket ...")`) and `mysqladmin`.

PHP talks to MySQL through its own driver, mysqlnd, and it words it differently. This one I did run, on PHP 8.3.6 with mysqlnd 8.3.6, Ubuntu 24.04:

```log
PDO: SQLSTATE[HY000] [2002] No such file or directory
host=localhost  socket=(default)  -> [2002] No such file or directory

```

If you've ever deployed Laravel or WordPress, you've seen that `SQLSTATE[HY000] [2002]` line. Same error, different costume.

It almost always appears at connect time, on the very first attempt, on a laptop or a dev box. That timing matters. An error that appears instantly, before any query, is about getting to the server, not about anything the server decided.

## Look at the number in the brackets first

Everyone reads the `2002`. Almost nobody reads the `(2)` at the end, and that's the part that tells you what actually went wrong. It's the operating system's error number from the `connect()` call on the socket file, and on Linux there are three you'll meet:

| What you see                    | errno        | What it means                                                                                                   |
| ------------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------- |
| (2) / No such file or directory | ENOENT       | There's no socket file at that path. Server stopped, or it put its socket somewhere else.                       |
| (111) / Connection refused      | ECONNREFUSED | A socket file exists but nothing is listening on it. A stale leftover from a server that crashed or was killed. |
| (13) / Permission denied        | EACCES       | The server is up and listening, but your user can't get into the directory or open the file.                    |

That table is the whole triage. Two minutes, tops:

```bash
# Is a mysqld process running at all?
ps aux | grep '[m]ysqld'
systemctl status mysql        # Debian/Ubuntu service name; it's mysqld on RPM-based distros

# Which Unix sockets are actually being listened on, and by whom? (run on the database host)
sudo ss -xlp | grep -i mysql

# What path is your client trying? It's the one in the quotes of the error.
ls -l /var/run/mysqld/mysqld.sock

```

If `ss` shows mysqld listening on `/tmp/mysql.sock` and your error quotes `/var/run/mysqld/mysqld.sock`, stop reading and jump to the fix. The server's fine. Your client and your server disagree about where the door is.

One more thing worth checking right here, because it's the near-miss: if your error says `ERROR 2003` and `Can't connect to MySQL server on '127.0.0.1:3306' (111)`, the client used TCP, not a socket. Different article, different fixes. That's [ERROR 2003](https://ggorantala.dev/mysql-error-2003-cant-connect-to-server/?ref=ggorantala.dev), and the [comparison of 2002, 2003, 1045 and 1130](https://ggorantala.dev/mysql-connection-errors-compared/?ref=ggorantala.dev) lays out how far each one got.

### Why "localhost" doesn't mean what you think

Here's the bit that cost me the most time, years ago, and still catches people weekly.

To the `mysql` client and anything built on libmysqlclient (and to PHP's mysqlnd), `localhost` is not a network address. The [connection options page](https://dev.mysql.com/doc/refman/9.7/en/connection-options.html?ref=ggorantala.dev) says it plainly: on Unix, connections to `localhost` use a Unix socket file by default. A Unix socket is a special file the server creates on disk; local clients open it like a pipe, with no TCP involved at all.

`127.0.0.1` is different. It forces TCP to port 3306 on the loopback interface.

So these two commands, which look identical to a human, go to two completely different places:

```bash
mysql -h localhost -u app -p     # Unix socket file
mysql -h 127.0.0.1 -u app -p     # TCP, port 3306

```

And the port flag? With `localhost`, it's ignored. I proved that to myself with PHP, pointing at port 3307 where nothing exists, and getting a socket error instead of a TCP one:

```log
$ php -r '... mysqli_connect("localhost","app","x","ledger",3307) ...'
2002 No such file or directory
$ php -r '... mysqli_connect("127.0.0.1","app","x","ledger",3307) ...'
2002 Connection refused

```

The first never touched port 3307\. It went straight for the socket. If you run MySQL in Docker published on 3307 and type `mysql -h localhost -P 3307`, you get ERROR 2002, and you'll stare at that port number for a long time wondering why it's being ignored. It is.

Notice something else in that second line. mysqlnd reports the **TCP** refusal as 2002 too. The `mysql` CLI would call that 2003\. So if you're in PHP, the number alone doesn't tell you socket vs TCP. The text does: "No such file or directory" is a socket path that doesn't exist, "Connection refused" against `127.0.0.1` is a closed port. That one surprised me; I'd assumed 2002 always meant socket everywhere.

## Reproduce all three variants (no server needed)

Because the client raises this error before any server is involved, you don't need a MySQL server to reproduce it. That's what makes this lab nice: it's safe to run anywhere, and it isolates the client's behaviour completely.

What I used: Ubuntu 24.04, PHP 8.3.6 CLI with the `mysqli` and `pdo_mysql` extensions (mysqlnd 8.3.6), and Python 3 for faking sockets. On Ubuntu that's `sudo apt install php-cli php-mysql`. The domain is an invoice-archive job that connects to a `ledger` schema as `app`; the credentials are junk on purpose, since we never get far enough to use them.

1. Write the probe. It takes a socket path and tries it:

```php
<?php
// t2.php: connect via a specific Unix socket and print what the client says
mysqli_report(MYSQLI_REPORT_OFF);
$sock = $argv[1];
$m = @mysqli_connect('localhost', 'app', 'x', 'ledger', 3306, $sock); // 'localhost' + socket path = socket transport
printf("socket=%s -> [%d] %s\n", $sock, mysqli_connect_errno(), mysqli_connect_error());

```

1. **Missing socket, the `(2)` case.** Point it at a path that doesn't exist:

```log
$ php t2.php /tmp/lab/missing.sock
socket=/tmp/lab/missing.sock -> [2002] No such file or directory

```

1. **Stale socket, the `(111)` case.** Create a socket file, then close it without anyone listening. That's what a `kill -9`'d server leaves behind:

```bash
python3 -c 'import socket; s=socket.socket(socket.AF_UNIX); s.bind("/tmp/lab/stale.sock"); s.close()'
ls -l /tmp/lab/stale.sock     # srwxr-xr-x ... stale.sock  (the file is there)

```

```log
$ php t2.php /tmp/lab/stale.sock
socket=/tmp/lab/stale.sock -> [2002] Connection refused

```

The file exists. Nothing's behind it.

1. **Permission denied, the `(13)` case.** A real listener in a directory your user can't enter, then connect as an unprivileged user:

```bash
mkdir -p /tmp/lab/locked
python3 -c 'import socket,time; s=socket.socket(socket.AF_UNIX); s.bind("/tmp/lab/locked/mysqld.sock"); s.listen(1); time.sleep(30)' &
sudo chmod 700 /tmp/lab/locked
sudo -u nobody php /tmp/lab/t2.php /tmp/lab/locked/mysqld.sock

```

```log
socket=/tmp/lab/locked/mysqld.sock -> [2002] Permission denied

```

There's a listener this time. The OS wouldn't let `nobody` reach it.

How you know you've got it: the code is 2002 and the text matches one of the three rows in the table. If you instead get `2002 Connection refused` with host `127.0.0.1`, you're testing TCP, not a socket.

With a real server on a laptop you can watch the CLI version: `sudo systemctl stop mysql`, then `mysql -u root -p` should print the `ERROR 2002 ... (2)` line from the top of this post, since on Debian/Ubuntu packages the server removes its socket on a clean stop. I didn't run that one here.

Teardown: `rm -rf /tmp/lab`. If the background `python3` is still sleeping, it exits on its own after 30 seconds.

## What's going on, roughly

The client was told (explicitly, or by defaulting to `localhost`) to use a Unix socket. It tried to open the socket file at a compiled-in or configured path. That open failed, so it gave up with 2002, carrying the OS reason in brackets. The server, if one is even running, never knew.

## Where the client gets that path from

The socket path in the error isn't random, and it's often not the one the server is using. That mismatch is the cause half the time.

The MySQL default compiled into the source is `/tmp/mysql.sock`. That's what the manual's [page on protecting or changing the socket file](https://dev.mysql.com/doc/refman/9.7/en/problems-with-mysql-sock.html?ref=ggorantala.dev) lists, and it notes that some distribution formats use something else, such as `/var/lib/mysql` for RPMs. Debian and Ubuntu packages use `/var/run/mysqld/mysqld.sock`, which is exactly what this workspace's Ubuntu-built PHP has baked in as `mysqli.default_socket`. Homebrew's MySQL on a Mac sticks with `/tmp/mysql.sock`.

Now picture a Mac with Homebrew MySQL (socket in `/tmp`) and a PHP or Python client from somewhere else that expects `/var/run/mysqld/mysqld.sock`. Both are working correctly. They've just never met.

The client picks its path in this order, highest first: a `--socket` option on the command line, then the `socket` option in the `[client]` section of an option file, then the `MYSQL_UNIX_PORT` environment variable (which the [environment variables page](https://dev.mysql.com/doc/refman/9.7/en/environment-variables.html?ref=ggorantala.dev) describes as the default socket file used for connections to `localhost`), then the compiled-in default. PHP has its own knobs: `mysqli.default_socket` and `pdo_mysql.default_socket` in `php.ini`, or `unix_socket=` in a PDO DSN.

The server decides its path from the `socket` setting in the `[mysqld]` section. You can ask a running server where it put it, from any session that works (a TCP one, for instance):

```sql
SELECT @@socket, @@port, @@hostname, @@version;

```

My first real dead end with this error, on a dev VM a long time ago, was restarting MySQL three times. It seemed sensible: "can't connect to server" sounds like "server's down", and restarting fixes down. The server was up every time. Its socket was in `/var/lib/mysql/mysql.sock` and the client wanted `/tmp/mysql.sock`. Running `SELECT @@socket` over TCP would've ended it in ten seconds.

There's a quieter way to lose the socket, too. The [manual's "can't connect" page](https://dev.mysql.com/doc/refman/9.7/en/can-not-connect-to-server.html?ref=ggorantala.dev) mentions a cron job that cleans old files out of `/tmp`. The server keeps running, happily serving TCP, and local socket clients start failing days after the last restart. If your server's uptime is longer than the age of the problem, think about `/tmp` cleaners (systemd-tmpfiles on many distros).

## Fixing it properly

Go by the bracket number.

**`(2)`, no file, and no mysqld running.** Start it, and if it won't start, read why instead of retrying:

```bash
sudo systemctl start mysql
sudo journalctl -u mysql -n 50 --no-pager
sudo tail -n 50 /var/log/mysql/error.log     # Debian/Ubuntu default error log location

```

A server that dies at startup is its own problem (a port clash, say, or a variable removed in an upgrade), and ERROR 2002 is only the symptom you saw from the client side.

**`(2)`, no file, but mysqld IS running.** The paths disagree. Make them agree in one place, the option file both sides read, instead of patching each client:

```ini
[mysqld]
socket=/var/run/mysqld/mysqld.sock

[client]
socket=/var/run/mysqld/mysqld.sock

```

Changing `[mysqld]` needs a server restart; `socket` isn't something you can change on a running server. For PHP, set `mysqli.default_socket` and `pdo_mysql.default_socket` to the server's real path in the right `php.ini` (the CLI and FPM often read different files). Don't fix this with a symlink from one path to the other. It works until the next reboot clears `/var/run` and you're back here with no memory of the symlink.

**`(111)`, stale socket.** The server isn't really running, it just left the file. Check with `ps`, look in the error log for why it died, then start it. A clean start replaces the stale file.

**`(13)`, permission denied.** Your user can't traverse the directory. On Debian/Ubuntu, `/var/run/mysqld` belongs to the `mysql` user; if someone tightened its permissions, put them back rather than adding your app user to the `mysql` group. If you moved the data directory or the socket to a custom path, AppArmor or SELinux profiles may also block it; the error log and `dmesg` will show the denial.

**You meant to use TCP all along.** This is the Docker case, and it's the most common one I see now. MySQL runs in a container published on the host, nothing runs locally, and the host's client defaults to the socket. Tell it to use TCP:

```bash
mysql -h 127.0.0.1 -P 3306 -u app -p
# or keep "localhost" and force the transport
mysql -h localhost --protocol=TCP -P 3306 -u app -p

```

In PHP, set `DB_HOST=127.0.0.1` instead of `localhost`. Inside the container itself, `docker exec -it db mysql -u root -p` works over the container's own socket, which is why "it works with docker exec" is a useless data point here. A container's socket is a file inside the container's filesystem. Your host can't see it unless you mount it.

What none of these is: `chmod 777` on the socket or its directory, or reinstalling MySQL. The first opens your server to every local user. The second wipes your config and usually leaves the mismatch exactly as it was.

## Getting the structure right up front

Pick a transport per environment and write it down. On a laptop with containers, that's TCP, always, with `127.0.0.1` and an explicit port in every connection string, so the socket never comes into play. On a VM or bare metal where the app shares the host with MySQL, the socket is fine (it skips the TCP stack), but then the path lives in exactly one option file and every client reads it.

Java apps get a pass on this one. Connector/J talks TCP to `localhost` by default, so a Java app never shows ERROR 2002; when it can't reach the server you get a `Communications link failure` instead, which is [its own article](https://ggorantala.dev/mysql-communications-link-failure/?ref=ggorantala.dev). A Spring Boot service and a PHP admin panel on the same box can disagree about whether MySQL is up, and both be right.

My laptop setup for the invoice-archive job looks like this, and it hasn't produced a 2002 in a long time:

```ini
# ~/.my.cnf  (chmod 600; mysql reads [client] from here)
[client]
host=127.0.0.1
port=3306
protocol=TCP

```

Credentials for real accounts go in a login path (`mysql_config_editor`), not in this file. And the app account is its own `user@host`, never root; if that last part is fuzzy, the [post on MySQL accounts as user@host](https://ggorantala.dev/mysql-user-host-accounts/?ref=ggorantala.dev) explains why `'app'@'localhost'` and `'app'@'%'` aren't the same account, which bites the moment you switch from socket to TCP.

## Keeping it from coming back

For a laptop error, prevention is mostly making the failure loud and early. A `make db-check` or a Compose healthcheck that runs `mysqladmin ping` over the same transport your app uses catches a stopped server before your test suite reports 400 failures. In CI, connect with `127.0.0.1` and an explicit port, never `localhost`, so a runner image with a different PHP build can't quietly switch you to a socket path that doesn't exist on it.

On servers, alert on the mysqld process and on the error log, not on socket connections; a socket that vanished under a `/tmp` cleaner while TCP keeps working will only show up in local tools. If your socket lives in `/tmp`, move it, or exclude it from the tmp cleaner.

Version notes. The 2002 code, the `CR_CONNECTION_ERROR` symbol and its message format are unchanged in the current 9.7 client error reference; I checked it against 9.7, and the format is the same one older 5.x and 8.0 clients print. As of the October 2026 releases (9.7.4 LTS, 8.4.13 LTS and the 26.10 Innovation release) nothing about socket defaults changed that I could find. What does change between machines is the packager's socket path and the PHP build's `default_socket`, so re-check both after moving from apt to Homebrew, or after upgrading PHP.

For this one I checked the three OS-level variants in a real client, the port-ignored behaviour, the error reference entry for 2002 and 2003, and the manual's pages on connection options, socket location and environment variables. It's a short story once you know to read the brackets.

## If you remember nothing else

- ERROR 2002 is raised by the client library. No server saw your request, so stop checking the password.
- Read the number in brackets: `(2)` no socket file, `(111)` stale file with nobody home, `(13)` permissions.
- `localhost` means the Unix socket and ignores `-P`; `127.0.0.1` means TCP. For Docker on your laptop, you want TCP.
- When mysqld is running and you still get `(2)`, `SELECT @@socket` over TCP shows where the server put its socket. Point `[client]` at the same path.
- In PHP, 2002 covers TCP refusals too. "No such file or directory" is the socket; "Connection refused" against `127.0.0.1` is a closed port.

## Questions people ask about ERROR 2002

### How do I fix ERROR 2002 when MySQL runs in Docker?

Your host's client is looking for a socket file that only exists inside the container. Connect with `mysql -h 127.0.0.1 -P 3306 -u app -p` (use the port you published), or add `--protocol=TCP`. If you then get `ERROR 1130` or `ERROR 1045`, you've reached the server and the account's host part is the next thing to look at.

### Why does 127.0.0.1 work but localhost doesn't?

To MySQL clients on Unix, `localhost` means "use the Unix socket file" and `127.0.0.1` means "use TCP on the loopback interface". If the socket path is wrong or missing but the server listens on TCP 3306, only `127.0.0.1` works. The fix is either to always use `127.0.0.1` or to point the client's `socket` option at the server's real socket.

### Where is mysql.sock on my system?

The MySQL source default is `/tmp/mysql.sock`, which Homebrew keeps. Debian and Ubuntu packages use `/var/run/mysqld/mysqld.sock`, and RPM-based installs typically use `/var/lib/mysql/mysql.sock`. The reliable answer is the server's own: run `SELECT @@socket;` over any working connection, or `sudo ss -xlp | grep mysql` on the host.

### What does SQLSTATE\[HY000\] \[2002\] mean in Laravel or PHP?

It's PHP's mysqlnd driver reporting it couldn't connect. "No such file or directory" means `DB_HOST=localhost` sent it to a socket file that doesn't exist; "Connection refused" means nothing is listening on the TCP host and port. Set `DB_HOST=127.0.0.1` and the right `DB_PORT` for a container, or set `DB_SOCKET` to the server's real socket path on a shared host.