MySQL cannot connect via localhost

On an Apache server, MySQL can’t connect when you use localhost, but it work when you chane to IP address

When you use “localhost”, it use socket for connecting to MySQL server, this is faster than using TCP/IP connection, that is used when you use IP address to connect to MySQL server.

First find out socket path. To do this login to MySQL server, run

mysql socket

See if you can connect using this socket with command

login to mysql using socket

In this cause, login to MySQL using socket worked.

I created a simple test PHP script to verify MySQL connection, it was able to connect to MySQL server using “localhost”.

Same script did not work when i try access it using web server. So the problem is web server user not able to connect to MySQL socket. You need to check permission for socket and parrent folders. In this case problem is fixed by running

You can verify enabling SSH access for web server user, then connect to MySQL using command line or try access socket file as apache user.

MySQL Socket Path in php.ini

When a PHP application use localhost to connect, PHP find location of socket from php.ini, you need to verify this path set in php.ini is same as the socket path used by MySQL server.

If path is differnt, you need to make it same. You can either modify php.ini or MySQL server config file.

Need help with Linux Server or WordPress? We can help!

Leave a Reply

Your email address will not be published. Required fields are marked *