yivi
yivi

Reputation: 47648

Running composer install and then copying project files in a docker project

Trying to understand this bit of Dockerfile that I found in a PHP project.

COPY composer.json composer.lock ./
RUN set -eux; \
    composer install --prefer-dist --no-dev --no-autoloader --no-scripts --no-progress --no-suggest; \
    composer clear-cache

COPY . ./

Lines 1 and 2 copy composer definition files and run composer install, so far so good.

But immediately it would seem that all the project files (which would include the aforementioned composer definition files) are copied to the same destination.

What is gained by not running the composer install after the. COPY . ./ step? If on the host composer install had already ran, woudn't that overwrite the work done in the first two lines?

Upvotes: 0

Views: 1608

Answers (1)

Federkun
Federkun

Reputation: 36989

You take advantage of docker's cache when you try to build the docker image again. Let's say you have this:

COPY . ./

RUN set -eux; \
    composer install --prefer-dist --no-dev --no-autoloader --no-scripts --no-progress --no-suggest; \
    composer clear-cache

This is fine, and the end result will be the same. The difference is that if you change any file in your repository, then all the instruction from the COPY will ran again. This mean that if you change anything ( maybe you added an image, or change a css file, or deleted a php file), you will re-install all the dependencies, even if you don't really need to. And the composer install will take its (long) time as well. Time that you can save.

Now take your example:

COPY composer.json composer.lock ./
RUN set -eux; \
    composer install --prefer-dist --no-dev --no-autoloader --no-scripts --no-progress --no-suggest; \
    composer clear-cache

COPY . ./

Now the only time you need to install again your packages, is when composer.json or composer.lock changes. You don't trigger it every time.

Upvotes: 3

Related Questions