Can't connect to MySQL using 'localhost' but using '127.0.0.1' it's ok?

My /etc/hosts file looks like this:

127.0.0.1 localhost

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

I found while building the server, that although i could ping localhost successfully, in certain configuration files for services like Postfix and Apache and Dovecot, I needed to specify 127.0.0.1 instead of localhost in order to make them work.

I also needed to change the configuration files of certain database driven websites, which used localhost to connect to MySQL.

I've tried various modifications to the hosts file, but nothing I've tried so far has helped.

The server is running Ubuntu 12.04.02 LTS. It does not have selinux installed and the above situation remains even after setting IPtables default policies to accept and flushing them.


One thing you might check is (which requires you to login to the MySQL console) - check to make sure that you have permissions to login to root via localhost.

mysql -h 127.0.0.1 -u root -p

-- Once you have successfully logged in --

mysql> select user,host from mysql.user;
+------+--------------------------------+
| user | host                           |
+------+--------------------------------+
| root | 127.0.0.1                      | 
| root | ::1                            |
| root | localhost                      | <-- Make sure you have a localhost entry for root
+------+--------------------------------+
3 rows in set (0.00 sec)

Just throwing it out there, just in case this is what the issue is.


Most MySQL clients are odd in the fact that if you specify the host as localhost, they alias that to a socket connection instead of a TCP connection. Your options are to either stick with 127.0.0.1 or, if the client supports it (like the mysql CLI binary does with the --protocol flag), force it to use TCP instead of a unix socket.