Why COPY package*.json ./ precedes COPY . .?

This is a common pattern in Dockerfiles (in all languages). The npm install step takes a long time, but you only need to run it when the package dependencies change. So it’s typical to see one step that just installs dependencies, and a second step that adds the actual application, because it makes rebuilding the container go faster.

You’re right that this is essentially identical if you’re building the image once; you get the same filesystem contents out at the end.

Say this happens while you’re working on the package, though. You’ve changed some src/*.js file, but haven’t changed the package.json. You run npm test and it looks good. Now you re-run docker build. Docker notices that the package*.json files haven’t changed, so it uses the same image layer it built the first time without re-running anything, and it also skips the npm install step (because it assumes running the same command on the same input filesystem produces the same output filesystem). So this makes the second build run faster.

Leave a Comment