Skip to content
Latchkey

Rails "Mysql2::Error::ConnectionError: Can't connect to MySQL server" in CI

The mysql2 client tried to open a connection to the MySQL server and was refused. In CI the service container is usually not up yet, or the host, port, or socket the app uses does not match the running server.

What this error means

db:prepare or tests fail with "Mysql2::Error::ConnectionError: Can't connect to MySQL server on '127.0.0.1' (111)" or via a unix socket that does not exist.

bundler
Mysql2::Error::ConnectionError: Can't connect to MySQL server on '127.0.0.1' (115)

Common causes

The MySQL service was not ready

The job connected before the MySQL service container finished starting, so the connection was refused.

Wrong host or socket configuration

The app targets a unix socket or host the service does not expose, so the client cannot reach it over TCP.

How to fix it

Wait for the service health check

  1. Add a MySQL service with a health check.
  2. Connect over TCP to 127.0.0.1 on the mapped port.
  3. Run db:prepare only after the service is healthy.
.github/workflows/ci.yml
services:
  mysql:
    image: mysql:8
    env: { MYSQL_ROOT_PASSWORD: root }
    ports: ['3306:3306']
    options: >-
      --health-cmd "mysqladmin ping" --health-interval 10s --health-retries 5

Use TCP, not a missing socket

Point database.yml at host 127.0.0.1 and the mapped port instead of a unix socket that does not exist in CI.

config/database.yml
test:
  adapter: mysql2
  host: 127.0.0.1
  port: 3306

How to prevent it

  • Gate database steps on the MySQL service health check.
  • Connect over TCP to the mapped port in CI, not a local socket.
  • Keep credentials and host in sync with the service container.

Related guides

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