Common causes
- The MySQL or MariaDB service is stopped or crashed
- MySQL failed to start because the disk is full or a config error
- The client looks for the socket in a different path than the server creates it
- PHP uses 'localhost' (socket) while MySQL runs in Docker or on another host
- The MySQL process was killed for using too much memory
- Permissions stop the client from reading the socket's directory
How to fix it
- Check that MySQL is running. Run sudo systemctl status mysql (or mariadb / mysqld). If it is stopped, start it with sudo systemctl start mysql.
- Read why it stopped. Check sudo journalctl -u mysql -n 50 and /var/log/mysql/error.log. Look for 'No space left on device', InnoDB errors or 'Out of memory'.
- Check disk space. Run df -h. If the disk holding /var/lib/mysql is full, free space (old logs, backups) before starting MySQL again.
- Find the real socket path. Run mysqladmin variables | grep socket or check socket= in /etc/mysql/my.cnf. Make the client use the same path, for example pdo_mysql.default_socket in php.ini.
- Use TCP when MySQL is remote. If MySQL runs in Docker or another server, connect to 127.0.0.1 or its hostname instead of localhost. localhost forces a socket connection in the MySQL client and PHP.
- Check for OOM kills. Run dmesg | grep -i -E 'killed process.*mysqld'. If MySQL was killed, lower innodb_buffer_pool_size or add memory or swap.
Diagnose a missing MySQL socket
sudo systemctl status mysql --no-pager
sudo tail -n 50 /var/log/mysql/error.log
df -h /var/lib/mysql
ls -l /var/run/mysqld/
mysql -h 127.0.0.1 -P 3306 -u appuser -p How to stop it happening again
- Monitor disk space on the database server
- Enable MySQL to start at boot
- Size innodb_buffer_pool_size to leave RAM for other services
- Use 127.0.0.1 or a hostname when MySQL is not on the same machine