1

I'm trying the tutorial on how to dockerize a nodejs application here: https://nodejs.org/en/docs/guides/nodejs-docker-webapp/

What I don't understand is why we don't take this docker file

FROM node:14
WORKDIR /usr/src/app
COPY package*.json ./

RUN npm install
COPY . .

EXPOSE 8080
CMD [ "node", "server.js" ]

And simplify it to:

FROM node:14
WORKDIR /usr/src/app
COPY . .

RUN npm install


EXPOSE 8080
CMD [ "node", "server.js" ]

That is, why do we have to copy all the files after the npm install? Why not do it before since it will already include the package*.json?

John
  • 32,403
  • 80
  • 251
  • 422

2 Answers2

4

This is because of multi layer builds within Docker. Every layer(/step) is cached, so this way the NPM install will not be run every time you change the source code, but only when the package.json or package-lock.json is changed.

Bas
  • 337
  • 2
  • 16
  • So in my first Dockerfile, if I edit `package.json`, then docker will execute lines 3 and onwards. If I make an edit to a source file in my project but not change `package.json`, then docker will execute lines 6 and onwards. Is that the idea? – John Apr 30 '21 at 12:27
  • @John Exactly, same goes for `package-lock.json`. This might change while running `npm update`, which doesn't have to change `package.json` – Bas Apr 30 '21 at 12:31
1

Docker uses a layer mechanism to build your docker image so that when you change something in your app you don't have to rebuild the whole image instead you just rebuild the layers that are needed. If you copy package.json first and you run npm install then next time you build your image you won't have to install dependencies again unless you modify the package.json file