MySQL Connect through localhost doesn’t work but 127.0.0.1 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 127.0.0.1 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 127.0.0.1.
A valid entry may look like the following.
[root@zeus ~]# cat /etc/hosts | grep 127.0.0.1
127.0.0.1 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 = 127.0.0.1
bind-address = localhost
If you need to use localhost in the connection string instead of 127.0.0.1, you need to change it to the following.
bind-address = 0.0.0.0
This will make sure that mysql listens in all interfaces and will also be available in ‘localhost’.
IMPORTANT
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.