How to fix

Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’

MariaDB and MySQL logos

When working with MySQL / MariaDB database you can catch a strange error:

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

The same error in log files:

[ERROR] Can't start server : Bind on unix socket: No such file or directory
[ERROR] Do you already have another mysqld server running on socket: /var/run/mysqld/mysqld.sock ?

In the simplest case it will be solved by the ritual of off/on:

sudo killall -9 mysqld
sudo /etc/init.d/mysql start

or in modern style:

sudo killall -9 mysqld
systemctl start mysql

If off/on doesn’t help

Okey, now we really have a problem 🙂 Don’t panic! There are two most common causes:

  • Someone already uses /var/run/mysqld/mysqld.sock file.
  • MySQL or MariaDB can’t access this file.

First of all let’s see, who uses this file:

sudo lsof /var/run/mysqld/mysqld.sock

As a result, we can get:

COMMAND PID  USER   FD   TYPE  DEVICE     SIZE/OFF NODE NAME
mysqld  1299 mysql  6u   unix  0xf688b840 0t0      7877 /var/run/mysqld/mysqld.sock

Well, now we know who uses our socket file… Maybe you should `kill -9` it to release it (you know your situation better).

In the 2nd case, lsof prints:

...
lsof: status error on /run/mysqld/mysqld.sock: No such file or directory
...

There is no our file… Well, we can make it manually:

sudo mkdir -p /var/run/mysqld
sudo mkfifo /var/run/mysqld/mysqld.sock
sudo chown -R mysql /var/run/mysqld

In the first line we make full path to file.

The second line makes special file that will used by MySQL / MariaDB.

And in the third line we delegate access rights to mysql user (which used by MySQL / MariaDB).

Now it should works fine… Let’s start our server:

systemctl restart mysql

Be happy!