Mysql2::Error::ConnectionError in CI
The mysql2 adapter could not connect to the MySQL server. The service may not be ready, or the host/port/credentials are wrong. Connecting early to a starting database service is a common transient failure.
What this error means
Tests fail at connect time with Mysql2::Error::ConnectionError (can't connect, access denied, or unknown host). It can be intermittent while the MySQL service warms up.
Mysql2::Error::ConnectionError:
Can't connect to MySQL server on 'localhost' (111 "Connection refused")Common causes
Service still starting
MySQL takes longer to become ready than Postgres; tests connected before it accepted connections.
Host/port mismatch
Config points at the wrong host (127.0.0.1 vs the service alias) or a non-default port.
Credential or auth-plugin mismatch
User/password do not match the service, or the auth plugin (caching_sha2_password) is incompatible with the client.
How to fix it
Wait for MySQL and align config
Gate tests on MySQL readiness and point config at the right host/credentials.
until mysqladmin ping -h 127.0.0.1 --silent; do sleep 1; done
# DATABASE_URL: mysql2://root:root@127.0.0.1:3306/myapp_testMatch the auth plugin
- Use 127.0.0.1 rather than localhost to force TCP instead of a missing socket.
- Ensure the client supports the server auth plugin, or start MySQL with mysql_native_password.
- Set credentials via env to match the service.
How to prevent it
- Add a MySQL readiness gate before the test step.
- Use 127.0.0.1 and an explicit port to avoid socket issues.
- On self-healing managed runners (Latchkey), a transient failure to reach a slow-to-start MySQL service is auto-retried instead of failing the run.