Remove development dependencies

One Paragraph Explainer

Dev dependencies greatly increase the container attack surface (i.e. potential security weakness) and the container size. As an example, some of the most impactful npm security breaches were originated from devDependencies like eslint-scope or affected dev packages like event-stream that was used by nodemon. For those reasons the image that is finally shipped to production should be safe and minimal. Running npm install with a --production is a great start, however it gets even safer to run npm ci that ensures a fresh install and the existence of a lock file. Removing the local cache can shave additional tens of MB. Often there is a need to test or debug within a container using devDependencies - In that case, multi stage builds can help in having different sets of dependencies and finally only those for production.

Code Example – Installing for production

Dockerfile

  1. FROM node:12-slim AS build
  2. WORKDIR /usr/src/app
  3. COPY package.json package-lock.json ./
  4. RUN npm ci --production && npm clean cache --force
  5. # The rest comes here

Code Example – Installing for production with multi-stage build

Dockerfile

  1. FROM node:14.8.0-alpine AS build
  2. COPY --chown=node:node package.json package-lock.json ./
  3. # ✅ Safe install
  4. RUN npm ci
  5. COPY --chown=node:node src ./src
  6. RUN npm run build
  7. # Run-time stage
  8. FROM node:14.8.0-alpine
  9. COPY --chown=node:node --from=build package.json package-lock.json ./
  10. COPY --chown=node:node --from=build node_modules ./node_modules
  11. COPY --chown=node:node --from=build dist ./dist
  12. # ✅ Clean dev packages
  13. RUN npm prune --production
  14. CMD [ "node", "dist/app.js" ]

Code Example Anti-Pattern – Installing all dependencies in a single stage dockerfile

Dockerfile

  1. FROM node:12-slim AS build
  2. WORKDIR /usr/src/app
  3. COPY package.json package-lock.json ./
  4. # Two mistakes below: Installing dev dependencies, not deleting the cache after npm install
  5. RUN npm install
  6. # The rest comes here

Blog Quote: “npm ci is also more strict than a regular install”

From npm documentation

This command is similar to npm-install, except it’s meant to be used in automated environments such as test platforms, continuous integration, and deployment – or any situation where you want to make sure you’re doing a clean install of your dependencies. It can be significantly faster than a regular npm install by skipping certain user-oriented features. It is also more strict than a regular install, which can help catch errors or inconsistencies caused by the incrementally-installed local environments of most npm users.