Seagyn Davis

Run PHP and Composer commands via Docker

1 min read24 February 2021

I moved to a new machine recently and have been actively making sure that I don't have any reliance on the existence of this machine. All the config that I usually need is stored in a git repo along with a bunch of other useful things like aliases, common stuff I need to be installed, and my ssh config.

Along with this, I also don't want to have to install every bit of software on the planet. This made me search for a better way to use the PHP CLI and Composer. For me, this made sense to run them via Docker. If you use Laravel, this means you can run Artisan commands via Docker as well.

This requires you to have the Docker CLI installed locally (which is usually just Docker for Desktop or Docker Community Edition). Once that is done, you simply need to add the following aliases into a .bash_profile or .zshrc (and source them once you have):

alias php="docker run --rm --interactive --tty --volume $PWD:/app -w /app php:8.0-cli php"
alias composer="docker run --rm --interactive --tty --volume $PWD:/app composer/composer"

This uses the latest Composer and PHP 8 by default. You are free to modify this as you see fit.

Once you have sources your bash config (for example source ~/.zshrc), you can then simply run `php` or `composer` as you normally would.

php -v
composer -V

This first run will take a little while as it has to first pull the image down but after that, it's pretty quick and cleans up the container after it has run.

Happy containering.