What is the difference between localhost and 127.0.0.1?

And when does it matter?

Joel Clermont
Joel Clermont
2024-06-11

Often, we view localhost and 127.0.0.1 as interchangeable ways of referring to the local machine, but today I want to highlight a time when there's an important distinction between them.

When connecting to a MySQL service, if you specify the host as localhost it will attempt to connect via a Unix socket, something like /tmp/mysql.sock.

But if you specify 127.0.0.1, it instead uses TCP/IP to connect locally using port 3306 (or whatever you have configured).

When does this matter? Let's say you spin up a MySQL server in Docker. It could be for local development or for running a CI pipeline.

In this case, the MySQL socket is not exposed to the host machine, so a connection to localhost will fail. A connection to 127.0.0.1 will work though, assuming your exposing the right port in the Docker configuration.

I like to just keep things consistent, and always use the explicit 127.0.0.1 address.

Here to help,

Joel

P.S. Curious about using Docker in your CI pipeline or locally? We can help you get started. Hit reply or schedule a call.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.