Docker to run multiple PHP versions
When programming, I like to have the tools on my current shell. I use PHP 8 on a daily basis but from times to times you need to test something with older versions. Docker is really handy for this and I usually use a Dockerfile like this:
# change the version here
FROM php:7.4-alpine
COPY --from=composer /usr/bin/composer /usr/bin/composer
RUN apk add git bash
WORKDIR /srv
CMD ["php"]
Once you have this, build and run:
docker build -t php-tool .
docker run --tty --detach --rm --name php -v "$PWD:/srv" php-tool
# or
docker run -t -d --rm --name php -v "$PWD:/srv" php-tool
For the run command we allocate a pseudo tty (using -t
or --tty
) to keep the php
process open (as it will act as REPL). Combine that to -d
, --detach
and you’ll have a docker container running under the name of php
. /srv
is the workdir and I binded the current $PWD
(print working directory) to that location.
Now to use it, either start a shell using bash
and -t
with -i
(--interactive
to keep stdin open):
docker exec -ti php bash
bash-5.1# php --version
PHP 7.4.16 (cli) (built: Mar 6 2021 04:24:10) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
Or run scripts:
docker exec -t php composer update
Note that I strongly suggest to remove the vendor
directory as symbolink links may have been destroyed in the volume-bind process (using simple-php-unit
for example).