Skip to content
Latchkey

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".

WP-CLI
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

  1. Point DB_HOST at 127.0.0.1 (TCP) or the service container name.
  2. Match DB_USER, DB_PASSWORD, and DB_NAME to the service env.
  3. Re-run the wp command once the host resolves.
.github/workflows/ci.yml
services:
  mysql:
    image: mysql:8
    env:
      MYSQL_DATABASE: wordpress
      MYSQL_ROOT_PASSWORD: root
    ports:
      - 3306:3306

Wait for the database before running wp

Poll the port until MySQL answers so the first connection is not refused.

Terminal
until mysqladmin ping -h 127.0.0.1 -uroot -proot --silent; do sleep 2; done
wp db check --path=web/wp

How to prevent it

  • Use 127.0.0.1 over TCP for service databases, not localhost.
  • Gate wp commands behind a readiness probe on the DB port.
  • Keep wp-config DB constants driven by CI env, not hardcoded.

Related guides

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