18

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: > protobufjs@6.10.2 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 knative-serving-helloworld@1.0.0 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
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

2 Answers2

32

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
David Maze
  • 130,717
  • 29
  • 175
  • 215
  • 1
    Thanks, I've also found more information on `npm ci` and its behavior with `devDependencies` on this other question/answer: https://stackoverflow.com/questions/60065865/is-there-a-way-of-making-npm-ci-install-devdependencies-or-npm-install-not – cbdeveloper Dec 10 '20 at 12:42
5

It depends if you want to have exactly the same env everywhere. If yes, package-lock.json is needed. There is a nice post about it here: https://stackoverflow.com/a/64014814/4925213

bohme
  • 81
  • 5
  • I guess that since I'm installing `--only production`, the `package-lock.json` will be different than the one I have in my local dev environment, right? 'Cause there are some `devDependencies` in `package.json`. Should I leave it out and ignore the warning, then? – cbdeveloper Dec 10 '20 at 12:27
  • You should have "dev" flag for devDependencies in package-lock.json, so it should remain the same. When you are building for production devDependencies should be excluded using that flag. – bohme Dec 10 '20 at 12:41