MySQL Connect through localhost doesn’t work but works.


You may encounter an error while using localhost as your IP address in MySQL connection string in a configuration file. MySQL Connect through localhost doesn’t work but works.

How to troubleshoot

First thing you would check is the servers hosts file. This is to ensure that localhost is added in hosts file with IP address

A valid entry may look like the following.

[root@zeus ~]# cat /etc/hosts | grep   localhost localhost.localdomain localhost4 localhost4.localdomain4

If this is the case, then your issue certainly is different.

Then you should look for bind-address directive in MySQL configuration. You need to check this in MySQL configuration files. Main MySQL configuration file is /etc/mysql/my.cnf.

This line may either be absent or may not have the following values

bind-address = 
bind-address = localhost

If you need to use localhost in the connection string instead of, you need to change it to the following.

bind-address =

This will make sure that mysql listens in all interfaces and will also be available in ‘localhost’.


Please note that setting this make sure that MySQL listens in all interfaces. This means that attackers can reach the server MySQL over a public interface. You need to make sure that tcp port 3306 is blocked for traffic from public IP addresses. From a security perspective, not having this modification is advisable.