WordPress wp-cli "Error establishing a database connection" in CI
WordPress bootstrapped and tried to connect to the database with DB_HOST, DB_USER, and DB_PASSWORD from wp-config, and the connection was refused. In CI the host is usually wrong (localhost versus the service name) or the service is not ready yet.
What this error means
A wp db ..., wp core install, or wp search-replace step fails with "Error establishing a database connection" or a wrapped "Can't connect to MySQL server".
Error establishing a database connection. This either means that the username and
password information in your `wp-config.php` file is incorrect or that contact with
the database server at `localhost` could not be established.Common causes
DB_HOST does not match the CI service
Inside Actions service containers the database is reachable by its service label or 127.0.0.1, not the localhost socket that wp-config defaults to.
The database service is not accepting connections yet
The MySQL/MariaDB container is still starting when wp runs, so the first connection is refused.
How to fix it
Set DB_HOST to the service and use TCP
- Point DB_HOST at
127.0.0.1(TCP) or the service container name. - Match DB_USER, DB_PASSWORD, and DB_NAME to the service env.
- Re-run the wp command once the host resolves.
services:
mysql:
image: mysql:8
env:
MYSQL_DATABASE: wordpress
MYSQL_ROOT_PASSWORD: root
ports:
- 3306:3306Wait for the database before running wp
Poll the port until MySQL answers so the first connection is not refused.
until mysqladmin ping -h 127.0.0.1 -uroot -proot --silent; do sleep 2; done
wp db check --path=web/wpHow to prevent it
- Use
127.0.0.1over TCP for service databases, notlocalhost. - Gate wp commands behind a readiness probe on the DB port.
- Keep wp-config DB constants driven by CI env, not hardcoded.