DB / MySQL / 2002
CRITICAL

MySQL Can't connect to local MySQL server

A connection error indicating the MySQL client cannot establish a socket connection to the MySQL server process. It typically occurs when connecting to 'localhost'.

Common Causes

  • The MySQL server service (mysqld) is not running.
  • Incorrect socket file path or permissions for the MySQL socket.
  • Using 'localhost' which forces a socket connection, but the server is configured for TCP/IP only.
  • Firewall rules blocking the MySQL port (usually 3306) when connecting via TCP/IP.
  • Incorrect 'bind-address' configuration in the MySQL server's my.cnf file.

How to Fix

1 Check and Start MySQL Service

Ensure the MySQL server daemon is running on the host.

BASH
$ # On systemd systems (Ubuntu, CentOS 7+) sudo systemctl status mysql # If stopped, start it sudo systemctl start mysql # On older SysVinit systems sudo service mysql status sudo service mysql start

2 Verify Socket Connection

Check the location of the MySQL socket file and ensure your client is looking in the correct place.

BASH
$ # Find the socket file path from MySQL config sudo grep 'socket' /etc/mysql/my.cnf /etc/my.cnf 2>/dev/null # Common default path ls -la /var/run/mysqld/mysqld.sock # Connect using the explicit socket path mysql -u root --socket=/var/run/mysqld/mysqld.sock -p

3 Force TCP/IP Connection

Use '127.0.0.1' instead of 'localhost' to bypass socket and use the network loopback interface.

BASH
$ mysql -u root -h 127.0.0.1 -p

4 Check Server Bind Configuration

Ensure the MySQL server is configured to accept connections on the expected interface.

BASH
$ # Check the bind-address in MySQL config sudo grep 'bind-address' /etc/mysql/my.cnf /etc/mysql/mysql.conf.d/mysqld.cnf 2>/dev/null # Common values: # bind-address = 127.0.0.1 (localhost only) # bind-address = 0.0.0.0 (all interfaces) # Comment it out or set to 127.0.0.1 for local connections, then restart MySQL.