Once I was disappointed at dockerizing Nodejs applications. Runing npm install was like leaving earth for mars. Thanks to Yarn for saving my ass. But nowadays PHP composer has taken that place. Running composer install in Docker used to take a huge time and slow down CI/CD speed. But I’ve managed to speed up the build process with some ninja techniques.

Rule 1 Link to heading

Use prestissimo with composer. It’s a plugin to download packages in parallel. But I’d like to label it as Yarn of PHP. However, don’t forget to install prestissimo before running actual composer install.

RUN composer global require hirak/prestissimo

Before using this plugin, one of my Dockerfile used to take 5m49s to be built while taking only 2m4s with the plugin. Whoa!

If you are wondering how I am counting time:

$ time docker build --no-cache .

Rule 2 Link to heading

Don’t use composer install alone. Use the following options to save your time:

–no-scriptsDisables the execution of the scripts defined in the root package.
–no-interactionDo not ask any interactive question.
–no-autoloaderSkips autoloader generation.
–no-devExcludes suggestions from require-dev packages.
–prefer-distInstall packages from dist when available.

Here’s an example:

RUN composer install --no-scripts --no-interaction --no-autoloader --no-dev --prefer-dist

Rule 3 Link to heading

Add your composer.json, composer.lock files and run composer install before adding the main source code. The reason is pretty straightforward. These composer files won’t change frequently comparing with your main source codes. You’ll get the benefits from Docker cache.

ADD composer.json composer.lock ./
RUN composer install --no-scripts --no-interaction --no-autoloader --no-dev --prefer-dist
ADD . ./

If I sum up the whole thing, your Dockerfile might have this part to speed up the Docker build:

RUN composer global require hirak/prestissimo
ADD composer.json composer.lock ./
RUN composer install --no-scripts --no-interaction --no-autoloader --no-dev --prefer-dist
ADD . ./

Rule Nth Link to heading

Have you heard about dive? It’s a tool for exploring a docker image, layer contents, and discovering ways to shrink the size of Docker/OCI image. I used to use dive to find out improvement areas. To analyze a Docker image simply run dive with an image tag/id/digest:

$ dive <your-image-tag>

Or, if you want to build your image then jump straight into analyzing it:

$ dive build -t <some-tag> .

Very easy, isn’t it? Don’t forget to check on GitHub for more clear documentation.