Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache node_modules on Docker build with version?

Tags:

node.js

docker

To cache node_modules I add the package.json first then I run npm i inside docker image.

which is works great. but I also need to have version inside the package.json, and each deploy/build I increment the version number.

Because package.json has been changed, docker is not cache mode_modules because of it.

How can I cache node_modules in this senirio?

FROM node

# If needed, install system dependencies here

# Add package.json before rest of repo for caching
ADD package.json /app/
WORKDIR /app
RUN npm install

ADD . /app

# If needed, add additional RUN commands here
like image 241
Jon Sud Avatar asked Apr 25 '26 02:04

Jon Sud


1 Answers

You can achieve this cache using BUILD_VERSION along with package.json version.

ARG BUILD_VERSION=0.0.0

Set some default value to BUILD_VERSION, keep the same value from BUILD_VERSION as package.json version to ignore the npm installation process.

Suppose you have the version in package.json is 0.0.0 and build version should be 0.0.0 to ignore installation.

FROM node:alpine
WORKDIR /app 
ARG BUILD_VERSION=0.0.0
copy package.json /app/package.json
RUN echo BUILD_VERSION is $BUILD_VERSION  and Package.json version is  $(node -e "console.log(require('/app/package.json').version);")
RUN if [ "${BUILD_VERSION}" != $(node -e "console.log(require('/app/package.json').version);") ];then \
   echo "ARG version and Package.json is different, installing node modules";\
   npm install;\ 
   else \
   echo "npm installation process ignored";\
   fi

To ignore npm installation during the build, run build command with

docker build --no-cache --build-arg BUILD_VERSION=0.0.0 -t test-cache-image .

enter image description here

Now, if you want to install node_modules just update the run command and it will work as you are expecting but more control as compared to caching track.

docker build --no-cache --build-arg BUILD_VERSION=0.0.1 -t test-cache-image .

This will install node_modules if the package.json version did not match with build-version.

enter image description here

like image 61
Adiii Avatar answered Apr 27 '26 20:04

Adiii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!