Search code examples
dockernpmdockerfilepackage.jsondocker-build

Should I copy `package-lock.json` to the container image in Dockerfile?


Here is my Dockerfile:

FROM node:12-slim

ENV NODE_ENV=production

WORKDIR /

# COPY . . # COPY ENTIRE FOLDER ?

COPY ./package.json ./package.json
COPY ./dist ./dist

RUN npm install --only=production

EXPOSE 8080

ENTRYPOINT npm start

Here is my .dockerignore file:

node_modules

You see that I'm just copying package.json and not package-lock.json. I guessed that, since I'll be running RUN npm install to build the image, I thought that it should create its own package-lock.json.

But I got this warning during the build:

> Step #0: > [email protected] postinstall /node_modules/protobufjs
> Step #0: > node scripts/postinstall
> Step #0:
> Step #0: npm notice created a lockfile as package-lock.json. You should commit this file.
> Step #0: npm WARN [email protected] No repository field.    
> Step #0: 
> Step #0: added 304 packages from 217 contributors and audited 312 packages in 15.27s

So, should I add this to my Dockerfile?

COPY ./package-lock.json ./package-lock.json

Solution

  • You should absolutely copy the package-lock.json file in. It has a slightly different role from the package.json file: package.json can declare "I'm pretty sure my application works with version 17 of the react package", where package-lock.json says "I have built and tested with exactly version 17.0.1 of that package".

    Once you have both files, there is a separate npm ci command that's optimized for this case.

    COPY package.json package-lock.json .
    # Run `npm ci` _before_ copying the application in
    RUN NODE_ENV=production npm ci
    # If any file in `dist` changes, this will stop Docker layer caching
    COPY ./dist ./dist