Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node development with Docker - Why do we copy twice

Tags:

node.js

docker

I recently started getting into Docker. I am a NodeJS developer so thats what i focused my research on. I found out that people often do the following :

COPY package*.json ./
RUN npm install
COPY . .

Why cant we just use one COPY? I would expect it to look like this :

COPY . .
RUN npm install

Doesnt this copy the package.json too?

like image 482
Kevin.a Avatar asked Dec 08 '22 11:12

Kevin.a


2 Answers

It's because of caching. Each line in the Dockerfile creates a layer of the image.

By writing your COPY of the package.json and RUN npm install in their own lines, you don't execute those two commands unless package.json changes again and thus you get a speed up of the build process!

like image 97
niko Avatar answered Dec 10 '22 01:12

niko


Reason to improve the your image building time in your docker and use the existing cached. Let me tell you some real-time example what happens when you do the below command while building the image

COPY . .
RUN npm install
  1. copies all the files in the folder including the src file which you edited
  2. Docker compare the old one and the new one there is a change in the files so it reconstruct everything and flushes the cache
  3. so npm install will run again and pull all the dependencies again

Above Slows the building image

Solution Below

COPY package*.json ./
RUN npm install
  1. When you Copy the package*.json it will compare the old one and new one

  2. if there is no change it won't flush cache and npm install will remains the same

For the purpose of the speeding up building the image

like image 29
Aravinth Raja Avatar answered Dec 10 '22 00:12

Aravinth Raja