If you get an error like below when trying to connect to your MySQL server from the terminal, you can solve the issue by following the steps below.


$ mysql -u root
mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!

Update MySQL server config


Update my.cnf as follows, save and exit.


# Assuming that this is where you config file is located
$ sudo nano /etc/mysql/my.cnf

# Update the 'socket' config as follows
[client]
socket = /var/lib/mysql/mysql.sock

[mysqld_safe]
socket = /var/lib/mysql/mysql.sock

[mysqld]
socket = /var/lib/mysql/mysql.sock

Restart MySQL server


$ sudo service mysql restart
mysql stop/waiting
mysql start/running, process 6372

Update permissions


You may not need this at all.


$ sudo chmod 777 /var/lib/mysql/mysql.sock
# OR
$ sudo chmod -R 755 /var/lib/mysql/

Test


$ mysql -u root
Welcome to the MySQL monitor.
........
........
mysql>

Alternative solution


Command below will work fine.


$ mysql -u your_username -pyour_password -h 127.0.0.1