wordpressdockerdocker-composewp-cli

Using WP-CLI locally with sites in docker


This is a weird one so bear with me.

I have a bunch of WordPress sites on my local machine for development. I use Docker with two containers php:8.2-apache and mariadb which I use as my host locally too.

When I view the sites in the browser the sites load fine however if I use wp-cli installed on the host machine it fails to connect to the database. In the wp-config.php file of a test site I have, I have define( 'DB_HOST, 'database' ); which works in the browser.

I need wp-cli installed on the host so I can use it without having to use docker exec.

Here is my docker-compose.yml file:

services:
  webserver:
    build: ./webserver
    container_name: webserver
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ~./sites:/var/www/html
    networks:
      - wordpress-network
    depends_on:
      - database

  database:
    image: mariadb
    container_name: database
    ports:
      - "3306:3306"
    volumes:
      - ./db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=password
    expose: 
      - 3306
    networks:
      - wordpress-network

networks:
  wordpress-network:
    driver: bridge

Any help would be greatly appreciated.

I have also tried define( 'DB_HOST', '127.0.0.1' ); and define( 'DB_HOST', 'host.docker.internal' ); but nothing fixes wp-cli's database connection errors.


Solution

  • For anyone coming here in future for a solution. I added a conditional to the wp-config.php file to check what is requesting the site.

    I also removed all networks sections from the docker-compose.yml file.

    Do not put this on a live site as you'll lock certain browsers out!

    You will need to change it to account for whatever browser you're using.

    define( 'LOCAL_STACK', 'docker' );
    if ( ENVIRONMENT === 'local' ) {
        if ( ! empty( LOCAL_STACK ) && LOCAL_STACK === 'docker' ) {
            if ( str_contains( $_SERVER['HTTP_USER_AGENT'], 'Chrome' ) !== false ) {
                define( 'DB_HOST', 'database' );
            } else {
                define( 'DB_HOST', '127.0.0.1' );
            }
        } else {
            define( 'DB_HOST', '127.0.0.1' );
        }
    } else {
        define( 'DB_HOST', '127.0.0.1' );
    }