+44 7575 472931[email protected]
HostAccentKnowledge BaseHosting, websites, SEO, and growth

Can't Connect to MySQL Server on localhost: Quick Fix

Can't connect to MySQL server on localhost? Restart the service, fix the socket, free up disk space, and clear port 3306 conflicts to get your database back.

VPS HostingWeb HostingWordPress
Terminal screen showing how to fix the can't connect to MySQL server on localhost error on a Linux VPS in 2026

Quick Answer: If you can't connect to MySQL server on localhost, the database service has almost certainly stopped. Run sudo systemctl restart mysql (or mariadb), then confirm with sudo systemctl status mysql. If it refuses to start, the cause is usually a full disk, a missing socket file, or a port conflict on 3306 — each fixable in a few minutes with the steps below.

Few things raise your pulse like a site that worked five minutes ago suddenly returning ERROR 2002 (HY000): Can't connect to local MySQL server through socket. Pages go blank. WordPress throws "Error establishing a database connection." Every refresh fails the same way.

Take a breath. This is one of the most common — and most fixable — problems on any Linux server, and you can almost always clear it in under 10 minutes once you know where to look.

We'll start with the fastest fix, then work through every likely cause in the order we actually see them, with the exact commands to run. On a managed stack like the one we run at Hostaccent — Cloudflare in front of Nginx → Apache, with MySQL/MariaDB on NVMe SSD storage — this error is one of the most frequent things our support team triages, so the playbook below comes straight from real incident notes, not theory.

What "Can't Connect to MySQL Server on localhost" Actually Means

When your application connects using the hostname localhost, MySQL doesn't touch the network at all. It connects through a local Unix socket file — usually /var/run/mysqld/mysqld.sock on Ubuntu and Debian. Point it at 127.0.0.1 instead and it switches to a TCP connection on port 3306. Same machine, two completely different paths.

That distinction matters. The error 2002 MySQL throws (Can't connect ... through socket) means the socket route failed — the server isn't there to answer. Error 2003 means the TCP route failed instead. Both are documented in the MySQL reference manual. Ninety-nine times out of a hundred, a 2002 on localhost means one thing: MySQL not running, or it died and never came back.

So this is rarely a "your password is wrong" problem — that's error 1045. It's a "the database process isn't alive" problem. Good news: that's easier to fix.

The Most Common Causes, Ranked by How Often We See Them

  1. The MySQL/MariaDB service stopped or crashed — by far the most common, often after the server ran out of memory and the kernel's OOM killer took the database down.
  2. The disk is full. MySQL can't write its files, so it refuses to start. A silently filling /var partition is the quiet killer.
  3. The socket file is missing or in the wrong place. The server puts the socket somewhere your app isn't looking.
  4. A port 3306 conflict or wrong bind-address. Something grabbed the port, or MySQL is bound to an interface your app can't reach.
  5. Table or InnoDB corruption after an unclean shutdown, forcing the engine into a recovery loop.
  6. Connection limit reachedmax_connections is maxed out and new requests are refused.

We'll fix each one.

Step-by-Step Fixes for Each Cause

Fix 1: Restart MySQL and read the status (solves most cases)

bash
sudo systemctl status mysql
sudo systemctl restart mysql

If your distro uses MariaDB, swap mysql for mariadb. Then read what the service actually says:

bash
sudo journalctl -u mysql --no-pager | tail -50

If it starts cleanly and stays up, you're done — reload your site and confirm. If it starts and dies within a few seconds, the logs you just pulled will name the real cause (almost always disk or corruption, both below).

Fix 2: Check for a full disk (the cause people miss)

After a plain restart, this catches more "won't start" cases than anything else. Run:

bash
df -h

Look at the partition holding /var/lib/mysql. At 100% — or even 95%+ — MySQL can't write and refuses to start. The usual culprit is runaway binary logs or a bloated error log.

Pro Tip: On a busy database, binary logs (/var/lib/mysql/*-bin.*) can quietly eat tens of GB. Set expire_logs_days = 7 (or binlog_expire_logs_seconds) so they auto-purge, and you'll likely never hit a full-disk database outage again. We rolled this default out across our fleet years ago and disk-full incidents dropped off a cliff.

To reclaim space safely, purge old logs from inside MySQL once it's running rather than deleting files by hand:

sql
PURGE BINARY LOGS BEFORE NOW();

Fix 3: Fix a missing or mismatched socket

If the service is running but you still get the socket error, your app and your server disagree on where the socket lives. Check the configured path:

bash
sudo grep -r socket /etc/mysql/

Confirm the file exists (ls -l /var/run/mysqld/mysqld.sock). If /var/run/mysqld went missing after a reboot, MySQL usually recreates it on start — if it doesn't, make sure that directory exists and is owned by the mysql user.

Insider Insight: Here's the trick nobody mentions mid-incident — if localhost keeps failing on the socket but the server is clearly up, switch your app's database host to 127.0.0.1. That forces a TCP connection on port 3306 and sidesteps the socket entirely. In WordPress, it's a one-line change to DB_HOST in wp-config.php. It's a perfectly valid permanent setup, not just a band-aid.

Fix 4: Clear a port 3306 conflict

See what's holding the port:

bash
sudo ss -tlnp | grep 3306

If nothing is listening, MySQL isn't bound — recheck the service. If a stray process grabbed 3306, stop it (or change MySQL's port and restart). Confirm bind-address is 127.0.0.1 for a local-only setup; binding to the wrong interface is a frequent misconfiguration we see at Hostaccent on fresh installs.

Fix 5: Recover from corruption (last resort — back up first)

If the logs mention InnoDB and the service crash-loops, you may have table corruption from an unclean shutdown. Before touching anything, copy /var/lib/mysql somewhere safe. Then add this temporarily:

ini
innodb_force_recovery = 1

Start MySQL, dump your data with mysqldump, remove the line, and restore cleanly. Only raise the number if 1 won't let it start — and never leave innodb_force_recovery on in normal operation. (If this feels above your pay grade during an outage, it's exactly the kind of thing a managed host handles for you.)

Fix 6: Free up maxed-out connections

If the error is intermittent under load rather than constant, you may be hitting the ceiling:

sql
SHOW VARIABLES LIKE 'max_connections';

The default is often 151. Bumping it to 200-300 buys time, but a connection pile-up usually points to slow queries or an undersized server — more on that next.

How to Confirm the Fix and Stop It Recurring

Once MySQL is back, verify end to end:

bash
mysqladmin -u root -p status

A reply with uptime in seconds means the server is answering. Reload your site; the database-connection error should be gone.

To keep it gone:

  • Give MySQL enough RAM. The OOM-kill → database-down chain is the single most common root cause we see at Hostaccent. A 1 GB box running WordPress, Apache, and MySQL together is living dangerously.
  • Monitor disk and set log expiry, as in Fix 2.
  • Enable auto-restart: sudo systemctl enable mysql brings the service back after a reboot.
  • Keep nightly backups. They turn a corruption incident from a disaster into a 10-minute restore.

If this error showed up alongside other failures, rule out the neighbours too — our guides on the 500 Internal Server Error in WordPress and the 403 Forbidden error cover symptoms that often appear in the same outage. For the settings above, MariaDB's documentation and the PHP mysqli manual are the references we point customers to.

When a Managed VPS Takes This Off Your Plate

Most "can't connect to MySQL server on localhost" outages trace back to a server that's simply under-resourced or unmonitored — and fixing that for good is more about infrastructure than commands. If you'd rather not be the one running systemctl restart at 2 a.m., a managed environment handles the memory headroom, monitoring, and backups for you.

Hostaccent's Linux VPS hosting starts at $7.99/mo for the Basic plan, with NVMe SSD storage, the Cloudflare → Nginx → Apache stack tuned for database workloads, and UK-based human support that actually reads your logs. As a UK-registered company running customer databases since 2018, this is the exact problem we keep alive 99.9% of the time. It won't suit you if you want full root-level control of every kernel parameter — that's what an unmanaged box is for — but for most sites, handing off the database babysitting is the upgrade. Planning a setup closer to your users? The Amsterdam VPS hosting guide covers the EU-region option, and if you're still locking in the foundations, the .com vs .net vs .io breakdown helps you pick the right domain.

Frequently Asked Questions

Why does it say can't connect to MySQL server on localhost when MySQL is installed?

Installed isn't the same as running. The error almost always means the service stopped or crashed — often after an out-of-memory event. Run sudo systemctl status mysql to check, then sudo systemctl restart mysql. If it won't stay up, check disk space and the error log for the real cause.

What does ERROR 2002 mean in MySQL?

Error 2002 means MySQL couldn't connect through the local Unix socket on localhost — the server isn't answering. That differs from error 2003 (a failed TCP connection) and error 1045 (wrong credentials). A 2002 is a "MySQL not running or socket missing" problem, never a password problem.

How do I fix a MySQL socket error?

First confirm MySQL is actually running. If it is, check that your app points to the correct socket path with sudo grep -r socket /etc/mysql/. The most reliable fix is switching your database host from localhost to 127.0.0.1, which uses TCP on port 3306 and bypasses the socket completely.

Why does MySQL keep stopping on my server?

Repeated crashes usually mean the server runs out of RAM and the OOM killer terminates MySQL, or the disk fills up. On small VPS plans running WordPress plus a web server, 1 GB of RAM is often too tight. Add memory, set log expiry, and enable automatic restart to break the cycle.

Can I prevent the can't connect to MySQL server on localhost error permanently?

You can make it rare. Give the database enough RAM, monitor disk usage, expire binary logs, run systemctl enable mysql, and keep nightly backups. A managed VPS like Hostaccent's removes most of the risk by handling resourcing, monitoring, and recovery for you.

Is localhost or 127.0.0.1 better for MySQL?

They behave differently: localhost uses a Unix socket, while 127.0.0.1 uses a TCP connection on port 3306. Sockets are marginally faster, but 127.0.0.1 is more predictable and avoids socket-path issues entirely. If you keep hitting socket errors, 127.0.0.1 is the safer choice.

Reviewed by

HostAccent Editorial Team · Editorial Team

Last updated

Jun 30, 2026

HostAccent Editorial Team publishes practical hosting guides, operations checklists, and SEO-focused tutorials for businesses building international web presence.

Discussion

Have a question or tip about this topic? Share it below — your comment will appear after review.

Your email stays private and is only used for moderation.

Why does it say can't connect to MySQL server on localhost when MySQL is installed?

Installed isn't the same as running. The error almost always means the service stopped or crashed — often after an out-of-memory event. Run sudo systemctl status mysql to check, then sudo systemctl restart mysql. If it won't stay up, check disk space and the error log for the real cause.

What does ERROR 2002 mean in MySQL?

Error 2002 means MySQL couldn't connect through the local Unix socket on localhost — the server isn't answering. That differs from error 2003 (a failed TCP connection) and error 1045 (wrong credentials). A 2002 is a "MySQL not running or socket missing" problem, never a password problem.

How do I fix a MySQL socket error?

First confirm MySQL is actually running. If it is, check that your app points to the correct socket path with sudo grep -r socket /etc/mysql/. The most reliable fix is switching your database host from localhost to 127.0.0.1, which uses TCP on port 3306 and bypasses the socket completely.

Why does MySQL keep stopping on my server?

Repeated crashes usually mean the server runs out of RAM and the OOM killer terminates MySQL, or the disk fills up. On small VPS plans running WordPress plus a web server, 1 GB of RAM is often too tight. Add memory, set log expiry, and enable automatic restart to break the cycle.

Can I prevent the can't connect to MySQL server on localhost error permanently?

You can make it rare. Give the database enough RAM, monitor disk usage, expire binary logs, run systemctl enable mysql, and keep nightly backups. A managed VPS like Hostaccent's removes most of the risk by handling resourcing, monitoring, and recovery for you.

Is localhost or 127.0.0.1 better for MySQL?

They behave differently: localhost uses a Unix socket, while 127.0.0.1 uses a TCP connection on port 3306. Sockets are marginally faster, but 127.0.0.1 is more predictable and avoids socket-path issues entirely. If you keep hitting socket errors, 127.0.0.1 is the safer choice.

Write for the Community

Have a tutorial, tip, or insight to share? Get published on the HostAccent Blog with your name, bio, and website link.

Become a Contributor

Need a faster setup for this workflow?