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.
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
- Add a MySQL service with a health check.
- Connect over TCP to 127.0.0.1 on the mapped port.
- Run db:prepare only after the service is healthy.
services:
mysql:
image: mysql:8
env: { MYSQL_ROOT_PASSWORD: root }
ports: ['3306:3306']
options: >-
--health-cmd "mysqladmin ping" --health-interval 10s --health-retries 5Use 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.
test:
adapter: mysql2
host: 127.0.0.1
port: 3306How 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.