How to resolve MySQL socket errors on a cPanel server?

This article defines the steps needed to resolve the error:
ERROR 2002: Can't connect to local MySQL sever through socket '/var/lib/mysql/mysql.sock' (2)

  1. Find where the MySQL socket should be located, normally in a redhat-based installation it is located in /var/lib/mysql/mysql.sock
  2. Check if the MySQL server is running and operational, use ps aux | grep mysql.

    root@servername ~# ps aux | grep mysql
    root 67220.00.146561132 ?S08:200:00 /bin/sh /usr/bin/mysqld_safe — datadir =/var/lib/mysql — socket=/var/lib/mysql/mysql.sock — log-error =/var/log/mysqld.log — \id-file=/var/run/mysqld/mysqld.pid
    mysql67640.12.6 128328 16904 ?Sl08:200:01 /usr/libexec/mysqld — basedir =/usr — datadir =/var/lib/mysql — user=mysql — pid-file=/var/run/mysqld/mysqld.pid — skip - external-locking — port=3306 --socket=/var/lib/mysql/mysql.sock
    root 70510.00.14044676 pts/0R+08:400:00 grep mysql

  3. If MySQL is not running, start the service with /etc/init.d/mysqld start or service mysqld start
    If MySQL is running run the command /usr/libexec/mysqld — print-defaults to see where the socket should be located according to the server. Look for --socket= ex: --socket=/var/lib/mysql/mysqld.sock
  4. Check /etc/my.cnf and ensure it has the correct location, save the file.
  5. Restart the MySQL server using /etc/init.d/mysqld restart or service mysqld restart
  6. Re-test the issue, if an issue remains make sure php has the correct location to refrence the socket using php -i | grep mysql.default_socket.
  7. If the command returns mysql.default_socket => no value => no value or an incorrect location edit /etc/php.ini and add or modify mysql.default_socket = ex: mysql.default_socket = "/var/lib/mysql/mysql.sock"

This should resolve any issues with the MySQL socket and be able to connect to the MySQL server.