DEV Community

Discussion on: Docker For Frontend Developers

Collapse
 
dimitrisnl profile image
Dimitrios Lytras

Why copy package.json separately?

Collapse
 
skythet profile image
Raimbek • Edited

I'll try answer with my bad english :)

It's very good question. Docker creates layers for each command COPY/ADD (and some others, you need to read documentation). In build time docker will see to the changes, if in some layer will detected change all below layers will be rebuild.

For example, assume we have like this Dockerfile:

 WORKDIR /app  
 COPY . /app  
 RUN npm install  
Enter fullscreen mode Exit fullscreen mode

And we will change source code very frequently, then docker will execute npm install for each change. It's very bad and not efficient. Because for each little change you will reinstall whole nodejs packages (and if you not using volume or cache it will take loooong time).

In this case:

 WORKDIR /app  
 COPY package.json /app
 RUN npm install
 COPY . /app  
Enter fullscreen mode Exit fullscreen mode

we will execute npm install only when package.json changes (some package added or removed so on).

Collapse
 
gautamkrishnar profile image
Gautam Krishna R

Great explanation. I too had the same question.

Collapse
 
akanksha_9560 profile image
Aks

right on :)

Collapse
 
dimitrisnl profile image
Dimitrios Lytras

Thank you for the detailed response! Your English are perfect btw.

Collapse
 
anantvir profile image
anantvir

The best explanation so far. Much better than 99% of the youtubers/tutorials online ! Thanks Raimbek ! This is awesome

Collapse
 
somangim profile image
SomangIm

Thank you! i was looking for this answer too

Collapse
 
daviddennis02 profile image
David Dennis • Edited

This is used to download the node package/dependencies your application needs.
With the help of adding node_modules folder to your DockerIgnore file, you only need to use the package.json file which gives a clear description of all the packages your node app needs inorder to run.