WP-CLI with Docker
Two articles ago we looked at using WordPress in Docker, and before that, we covered Docker compose. Today, we’ll give a brief overview of using WP-CLI in Docker.
I’m assuming that there’s no need to introduce WP-CLI to WordPress developers. It’s the principal tool for serious professional WordPress developers—a command line interface for WordPress. Instead of installing, updating, and editing things using the WordPress GUI, you can do it all using WP-CLI. If you are running automation tests in WordPress (and yes, you really should be checking the code you write for WordPress) then WP-CLI is essential.
How do we work with WP-CLI in Docker? We actually don’t just install it on our local machine but rather use it as a part of a container. Simple and easy as could be. To do this, first we need to use this docker-compose:
version: '3.1' services: wordpress: image: wordpress restart: always ports: - 8080:80 environment: WORDPRESS_DB_HOST: db WORDPRESS_DB_USER: exampleuser WORDPRESS_DB_PASSWORD: examplepass WORDPRESS_DB_NAME: exampledb # Keep your data volumes: - ./site:/var/www/html/ cli: image: wordpress:cli volumes: - ./site:/var/www/html/ db: image: mysql:5.7 restart: always environment: MYSQL_DATABASE: exampledb MYSQL_USER: exampleuser MYSQL_PASSWORD: examplepass MYSQL_RANDOM_ROOT_PASSWORD: '1' # Keep your data volumes: - ./db:/var/lib/mysql
If this looks like Chinese to you, you should probably check out our articles on Docker compose in this series. But for those of you who read the previous articles and know what’s going on here, you’ll notice that the main change is the addition of a container called cli:
cli: image: wordpress:cli volumes: - ./site:/var/www/html/
After we save the docker-compose file in its folder, we run it with the following command:
docker-compose up -d
Once the site is up and running on our machine’s IP on port 8080, we can run:
docker-compose run --rm cli bash
This will take us to a container that has WP-CLI in it and is connected to our local machine. All we have to do is navigate to the directory where WordPress is found (which you can find in docker-compose) and then run WP-CLI:
And that’s how it looks! Easy as pie! If you were successful in running it, give yourself a pat on the shoulder. You just ran docker-compose with three, count ‘em three containers. You’re getting pretty advanced here!
About the author: Ran Bar-Zik is an experienced web developer whose personal blog, Internet Israel, features articles and guides on Node.js, MongoDB, Git, SASS, jQuery, HTML 5, MySQL, and more. Translation of the original article by Aaron Raizen.