Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

What is the difference between localhost and 127.0.0.1?

And when does it matter?

Joel Clermont
Joel Clermont
2024-06-11

From our daily Laravel tips email. Get the next one in your inbox.

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.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.