Speedy Composer installs in Docker builds

I’m going to share a few optimisations you can make to speed up composer installs in Docker builds.

  1. Prestissimo
  2. Turn off Xdebug
  3. Composer install before codebase

1. Prestissimo

composer global require hirak/prestissimo

To leverage it in a Docker build, install Composer in your Dockerfile with the following:

RUN curl -sS https://getcomposer.org/installer | php && mv composer.phar /usr/local/bin/composer && composer global require hirak/prestissimo --no-plugins --no-scripts

2. Turn off Xdebug

RUN phpdismod xdebug

If youre installing PHP yourself as part of your image, you could also just not install Xdebug at all. It’s probably best to keep it out of production images anyway.

3. Composer install before codebase

If you make the assumption that you change your codebase more often than your Composer dependencies — then your Dockerfile should run composer install before copying across your codebase. This will mean that your composer install layer will be cached even if your codebase changes. The layer will only be invalidated when you actually change your dependencies.

# Install dependencies
COPY composer.json composer.json
RUN composer install --prefer-dist --no-scripts --no-dev --no-autoloader && rm -rf /root/.composer

# Copy codebase
COPY . ./

# Finish composer
RUN composer dump-autoload --no-scripts --no-dev --optimize

The rm -rf /root/.composer line is to remove Composer’s cache. This reduces the size of the resulting image. The location of the .composer directory may differ on the various Linux distributions.

Important: If you’ve already run Composer in your build context, your local vendor directory would overwrite the one in your build. The most convenient solution for this is to add /vendor/ to your .dockerignore file.

Software engineer

Software engineer