error mysql
MySQL Error 2002 - Connection Refused (Socket)
Understanding MySQL error 2002 - can't connect to the local MySQL server through the socket file. The server may not be running.
What It Means
MySQL error 2002 (CR_CONNECTION_ERROR) means “Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’.” This error occurs when trying to connect to MySQL via a Unix socket file, but the connection fails. The MySQL server is likely not running, or the socket file path is incorrect.
Common Causes
- MySQL server is not running
- MySQL crashed and the socket file was removed
- Socket file is in a different location than the client expects
- Insufficient permissions to access the socket file
- Using
localhostinstead of127.0.0.1(localhost uses the socket, while 127.0.0.1 uses TCP) - MySQL was installed but never started
- AppArmor or SELinux blocking socket access
How to Fix
Check if MySQL is running
# Check MySQL service status
sudo systemctl status mysql
sudo systemctl status mysqld # On CentOS/RHEL
# Check if the process is running
ps aux | grep mysql
# Start MySQL if it's not running
sudo systemctl start mysql
Find the correct socket file
# Find where the socket file is
find / -name "mysql.sock" -o -name "mysqld.sock" 2>/dev/null
# Check MySQL configuration for socket path
grep -r "socket" /etc/mysql/ 2>/dev/null
cat /etc/my.cnf 2>/dev/null | grep socket
Connect using TCP instead of socket
# Use 127.0.0.1 to force TCP connection
mysql -u root -p -h 127.0.0.1
# Or specify the protocol explicitly
mysql -u root -p --protocol=TCP
Fix socket path in configuration
# /etc/mysql/my.cnf or /etc/my.cnf
[client]
socket = /var/run/mysqld/mysqld.sock
[mysqld]
socket = /var/run/mysqld/mysqld.sock
Fix socket file permissions
# Check permissions on the socket directory
ls -la /var/run/mysqld/
# Fix permissions
sudo mkdir -p /var/run/mysqld/
sudo chown mysql:mysql /var/run/mysqld/
sudo chmod 755 /var/run/mysqld/
# Restart MySQL
sudo systemctl restart mysql
Create a symlink if paths differ
# If your client expects the socket at a different path
sudo ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock
Fix in application configuration
// Node.js - use TCP connection
const connection = mysql.createConnection({
host: '127.0.0.1', // TCP, not socket
port: 3306,
user: 'myapp',
password: 'password',
database: 'mydb'
});
// Or specify socket path explicitly
const connection = mysql.createConnection({
socketPath: '/var/run/mysqld/mysqld.sock',
user: 'myapp',
password: 'password',
database: 'mydb'
});
# Python - use TCP
connection = mysql.connector.connect(
host='127.0.0.1',
port=3306,
user='myapp',
password='password',
database='mydb'
)
Related Errors
- MySQL 2003 - Can’t connect via TCP: Similar issue but for TCP/IP connections instead of sockets.
- MySQL 1045 - Access denied: Connection succeeded but credentials are wrong.