Skip to content
Latchkey

MySQL "ERROR 2002 (HY000): Can't connect ... through socket" in CI

The MySQL client fell back to a local Unix socket (e.g. /var/run/mysqld/mysqld.sock) that does not exist on the runner because MySQL is a separate container reachable over TCP. The socket file is absent, so the connect fails with ERROR 2002.

What this error means

mysql or a migration tool fails with "ERROR 2002 (HY000): Can't connect to local MySQL server through socket". It happens when the host is localhost (which triggers a socket connection) instead of 127.0.0.1 (which forces TCP).

mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket
'/var/run/mysqld/mysqld.sock' (2)

Common causes

localhost forces a socket connection

With the MySQL client, localhost means "use the Unix socket". In CI the database is a TCP service, so there is no local socket to use.

Service not ready yet

If you do connect over TCP, the container may still be starting, which is transient and clears on retry.

How to fix it

Force TCP with 127.0.0.1

Use 127.0.0.1 (or --protocol=TCP) so the client connects over the network instead of a missing socket.

Terminal
mysql --protocol=TCP -h 127.0.0.1 -P 3306 -uroot -p"$MYSQL_PWD" -e 'select 1'

Point the app/URL at 127.0.0.1

.github/workflows/ci.yml
env:
  DATABASE_URL: mysql://root:${{ secrets.MYSQL_PASSWORD }}@127.0.0.1:3306/app

How to prevent it

  • Use 127.0.0.1/--protocol=TCP for MySQL in CI, never localhost.
  • Gate the connection on a readiness check.
  • On managed runners (Latchkey), self-healing auto-retries genuinely transient connection failures while the database finishes starting.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →