Avoid "localhost" when connecting to databases

by Leon Miller-Out

I've now run into trouble when using "localhost" as my database server address with a couple of unrelated database servers, namely MySQL and Microsoft SQL Server. At this point, it seems like a good rule of thumb to always use 127.0.0.1 instead of "localhost".

Shouldn't  "localhost" and 127.0.0.1 always be equivalent? One would think so. However, database clients sometimes don't treat them the same. MySQL will attempt to use unix sockets to connect to localhost, but TCP to connect to 127.0.0.1. I've seen this happen with Ruby on Rails. On my OS X workstation, MySQL's socket file isn't where the mysql2 gem expects it to be, so I either have to specify it in my database.yml or just use TCP instead.

MS SQL Server has a similar weird behavior. Using localhost will cause a SQL Server client (like SQL Server Management Studio) to attempt to connect using a non-TCP protocol. I'm not sure if it uses Shared Memory or Named Pipes, but suffice it to say that it doesn't always work. If you use 127.0.0.1, the client will use TCP to connect.

For more, see Wikipedia's entry on "localhost".