Using localhost
or 127.0.0.1
for WordPress database access is a common configuration choice, but the subtle differences between them can impact performance, compatibility, and troubleshooting. Here's a breakdown tailored to your server-savvy mindset:
What They Mean
Value |
Description |
---|---|
|
Connects via Unix socket (if available). Faster, avoids TCP overhead. |
|
Forces connection via TCP/IP loopback. Useful when socket isn't viable. |
⚙️ WordPress Configuration
In wp-config.php
, the DB host is defined like this:
define( 'DB_HOST', 'localhost' ); // or '127.0.0.1'
Key Differences
- Connection Method:
localhost
: Uses the MySQL socket file (e.g.,/var/lib/mysql/mysql.sock
).127.0.0.1
: Uses TCP/IP, even though it's local.
- Performance:
- Socket (
localhost
) is generally faster due to lower overhead. - TCP (
127.0.0.1
) adds a bit of latency but is more consistent across environments.
- Socket (
- Compatibility:
- Some setups (e.g., Docker containers, chrooted environments) may not expose the socket.
- TCP (
127.0.0.1
) avoids socket path issues and SELinux/AppArmor restrictions.
- Troubleshooting:
- If WordPress throws a “Can’t connect to database” error with
localhost
, switching to127.0.0.1
often resolves it. - You can test socket vs TCP with
mysql -h localhost
vsmysql -h 127.0.0.1
.
Advanced Notes
- RISP servers are using
mysqlnd
, socket connections are preferred and optimized, if available. - RISP servers are using CloudLinux MySQL Governor, TCP may be required.
- For remote DBs or containers, always use an IP or hostname—not
localhost
.
✅ Best Practices
- Use
localhost
if the socket is available and you're on a standard Linux/cPanel setup. - Use
127.0.0.1
if:
- You're in a containerized or isolated environment.
- You want consistent behavior across platforms.
- You're debugging connection issues.