Solving MySQL ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)

I came upon this error after installing the latest version of MySQL using yum and securing it.

The Error

With mysqld running I tried to run mysql as follows:

[ahmed@amayem ~]$ mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Different failed attempts:

Here are more attempts to get it working:

[ahmed@amayem ~]$ telnet 127.0.0.1 3306 
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
[ahmed@amayem ~]$ mysql -h 127.0.0.1
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)
[ahmed@amayem ~]$ mysql -h 127.0.0.1 -P 3306
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)
[ahmed@amayem ~]$ mysql -h 127.0.0.1 -P 3306 -u root
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)
[ahmed@amayem ~]$ mysql -h 127.0.0.1 -P 3306 -u root -p
Enter password: 
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

The Solution

[ahmed@amayem ~]$ cd /etc/init.d/
[ahmed@amayem init.d]$ ./mysqld stop
Stopping mysqld:                                           [  OK  ]
[ahmed@amayem init.d]$ sudo ./mysqld start
Starting mysqld:                                           [  OK  ]

Basically we just restarted mysqld. Now the error changes:

[ahmed@amayem init.d]$ mysql
ERROR 1045 (28000): Access denied for user 'ahmed'@'localhost' (using password: NO)

This is good, now we just need to use a user that has access, like root that was made when we secured the install.

[ahmed@amayem init.d]$ mysql -u  root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or g.

And we are in.

The Reason (Conjecture)

Since it started working after manually restarting mysqld, I would have to guess that when it was restared it made /var/lib/mysql/mysql.sock, which might have been missing. Unfortunately I didn’t check on its existence before, so I can’t confirm. If anyone has a reason please mention it in the comment section.

Ahmed Amayem has written 90 articles

A Web Application Developer Entrepreneur.

  • http://web-scents.blogspot.com/ Muhaimin

    really save the day. But my experience on centos 7 is different. I have to use systemctl

    • http://ahmed.amayem.com ahmedamayem

      Happy to be of service

      • http://web-scents.blogspot.com/ Muhaimin

        but this happen to me too often. Do you have any idea to prevent it from happening

        • http://ahmed.amayem.com ahmedamayem

          Does it happen after a reboot?

          • Infacq

            yes indeed

  • http://web-scents.blogspot.com/ Muhaimin

    have this answer checked. Let me know if this cause the mysql to stop

  • Marc Hauser

    That “solution” sucked. Even a mac users could do that.