skip to Main Content

I’m building a NodeJS application, and after each commit I build a docker image for it

As best practice, I copy packge.json and package-lock.json then run npm install then copy the rest of project content, to avoid recreate the packages and dependencies every time I change the code and rebuild the image, Dockerfile looks like this

FROM node:alpine

WORKDIR /app
COPY ./package.json ./package-lock.json ./
RUN npm ci

COPY . .

EXPOSE 80
CMD ["npm", "start"]

The problem is, when I update my project code I suppose to update the version number in package.json file, and if I did docker will not use the cached layer because the package.json is changed, how can I fix that? Can I move the package version number outside the package.json file?

I don’t plan to publish my project on npm as it is an internal project, can I ignore updating the version number in package.json? Will that affect anything?

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for @kshitij-joshi

    I have updated the Dockerfile and it works

    # https://stackoverflow.com/a/58487433
    # https://stackoverflow.com/a/73428012/3746664
    
    ######## Preperation
    FROM node:alpine AS deps
    
    COPY package.json package-lock.json ./
    RUN npm version --allow-same-version 1.0.0
    
    
    ######## Building
    FROM node:alpine
    
    WORKDIR /app
    
    COPY --from=deps package.json package-lock.json ./
    RUN npm ci
    
    COPY . .
    
    EXPOSE 80
    CMD ["npm", "start"]
    

  2. Even though updating the package.json is a best practice, it’s not mandatory to update it and won’t affect anything in your personal project. It’s mainly for npm publishing. In the future, if you plan to publish them, have your CI update the patch version during the publishing process.

    If maintaining a correct package.json is important for you, there are some interesting ideas here
    Bumping package.json version without invalidating docker cache

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search