Skip to content

Instantly share code, notes, and snippets.

@wnqueiroz
Created September 24, 2022 01:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save wnqueiroz/425ce7399e227a9be4e4b1719c225689 to your computer and use it in GitHub Desktop.
Save wnqueiroz/425ce7399e227a9be4e4b1719c225689 to your computer and use it in GitHub Desktop.
An efficient Dockerfile to build an image with NestJS with just the production dependencies
FROM node:16.17-alpine as builder
WORKDIR /usr/src/app
ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}
COPY package*.json ./
RUN npm i -g @nestjs/cli \
&& npm install
COPY . .
RUN npm run build
FROM node:16.17-alpine as runtime
ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}
ARG NODE_PORT=8080
ENV NODE_PORT=${NODE_PORT}
WORKDIR /usr/src/app
COPY --from=builder /usr/src/app/node_modules ./node_modules
COPY --from=builder /usr/src/app/package*.json ./
COPY --from=builder /usr/src/app/dist ./dist
CMD ["npm", "run", "start:prod"]
@wnqueiroz
Copy link
Author

wnqueiroz commented Sep 24, 2022

Overview

Controlling dependencies in NodeJS can come in handy if used wisely. Most people don't take the time to analyze what the final size of a generated image is. They usually run an npm install, build the project and start the application. With that in mind, I decided to explore how to build an efficient Dockerfile so that, when building an image, only production dependencies enter the build. The example here is for a NestJS project and can be tweaked for other frameworks just adapting to your needs.

This is capable of halving the size of a Docker image!

The use in a docker-compose.yml is also interesting because in it we specify that we want the development dependencies (running in a local environment, of course).

Usage with docker-compose.yml

version: "3"

services:
  app:
    build:
      context: .
      args:
        NODE_ENV: development
    ports:
      - 8080:8080
    command: npm run start:dev
    volumes:
      - .:/usr/src/app
      - node_modules:/usr/src/app/node_modules
    environment:
      NODE_PORT: 8080

volumes:
  node_modules:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment