MySQL cannot connect via "localhost", only 127.0.0.1

Solution 1:

MySQL will try to connect to the unix socket if you tell it to connect to "localhost". If you tell it to connect to 127.0.0.1 you are forcing it to connect to the network socket. So probably you have MySQL configured to only listen to the network socket and not to the file system socket.

What exactly is wrong with your unix socket is hard to tell. But I recommend you to read this page on the MySQL reference guide. This should help you.

UPDATE: Based on the updated question: The parameter "socket" should be something like this: "/var/lib/mysql/mysql.sock". This page in the Reference Manual has some more information.

Here you have the beginning of my /etc/my.cnf file:

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

Your file should be similar. Then your problem should be solved. Don't forget to restart the MySQL server before you test it.

Solution 2:

You may have IPv6 enabled, its very possible localhost resolves to the ipv6 localhost, that is not defined in your msql config.

ive also had a problem where i had to add 'localhost' in place of '127.0.0.1' to the allowed subnets for that user, dont understand why (i was using ipv4 and it was a while ago) but its worth a try.


Solution 3:

For me, OSX's builtin php is configured to use a different unix-socket than homebrew's mysql. Thus it can't connect via localhost which utilizes that socket.

I fixed it with a quick hack by symlinking php's configured socket-path to point to the one mysql actually uses.

sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

The following diagnostic commands were very helpful.

Check the default socket-paths used by php and mysql:

php -i | fgrep 'mysql.default_socket'
mysql -e 'show variables where variable_name = "socket"'

Connect using a specified socket:

php -r 'var_dump(mysql_connect("localhost:/tmp/mysql.sock", "user", "pass"));'
mysql --socket=/tmp/mysql.sock

Determine what kind of socket mysql client is using to connect:

lsof | egrep '^mysql .*(IPv|unix)'

Solution 4:

Could you check mysql/conf/my.conf (the directory structure should pretty much be the same on OSx) to see if skip-networking is uncommented? If so, add a # in-front of the line and restart the mysql-server.

I actually had a similar issue a while back (although that wasn't in OSx), so I thought it might be worth a shot.


Solution 5:

PHP is still trying to use the default socket location. This problem can appear if you have moved the MariaDB/MySQL folder from /var/lib/mysql to another location. In order to solve the problem you have to define the new socket's location in the /etc/php.ini file.

mysqli.default_socket =/newDBLocation/mysql/mysql.sock

Watch out, depending on which driver you use, you may have to specify the pdo_mysql.default_socket=!

In order to check your current directory run the following command in mysql:

select @@datadir;