Faster Docker builds with composer install ⚡

Iacovos Constantinou
2 min readOct 29, 2021
Photo by CHUTTERSNAP on Unsplash

When working with PHP projects and Docker, it is a good practice to include all the third party dependencies coming from composer install.

This really helps to reduce the time needed to spin off a new container. However, when not done right, it can significantly increase the build time.

Throughout this post we will see how we can avoid this and optimize composer install for docker builds.

Consider the following simple example, where we copy our source code before executing composer install

WORKDIR /my-cool-app
COPY . ./
RUN composer install --no-dev --no-interaction --optimize-autoloader

While this works, there is a major flaw; we don’t leverage Docker cache. Every time there is a change in our source code, the docker cache for composer install will be invalidated.

In real life, this will happen with almost every build, causing composer install to be executed even when there are no changes in our dependencies.

Not efficient, that’s for sure. But how can we avoid this? Consider the following example:

WORKDIR /my-cool-app
COPY composer.json ./
COPY composer.lock ./
RUN composer install --no-dev --no-interaction --no-autoloader --no-scripts
COPY . ./
RUN composer dump-autoload --optimize

--

--

Iacovos Constantinou

CTO at Qobrix, husband, father of two, blogging occasionally about web development