Wanna know some often overlooked good principles to containerise Node.js apps efficiently with 🐳 Docker?

- faster builds and when necessary ✅
- smaller images for faster deploys and smaller cold starts ✅

Read on👇
Principle #1
Create a comprehensive .dockerignore file to ignore all the files that aren't necessary to your Docker image build (docs, node modules, config files for ESLint, Jest, etc.).

- better Docker layer caching
- fewer files sent to the build context

=> faster builds 🏎
Principle #2
Use an appropriate base image.
=> faster builds 🏎
=> smaller resulting Docker image

Compare:
node:14.15.0-alpine: ~40MB 🥕
node:14.15.0: ~345MB 🍟

(7 characters to save 300MB, not bad)
Principle #3
Decouple 'npm install' from 'npm run build'

COPY package.json package-lock.json . # This line here
RUN npm install
COPY . .
RUN npm run build

The node modules are better cached and 'npm intall' runs only when necessary.

=> faster builds 🏎
Principle #4
Decouple the 'npm run build' output from the base files

Your app does not need the source files to run, so why keep them around to bloat our Docker image?

=> smaller final image 🥕
Bonus
Purge node modules from unnecessary files to reclaim some MBs in your final image.
For example, by using `node-prune`.

=> smaller final image 🥕
You can follow @RobinCsl.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.