Skip to content

Instantly share code, notes, and snippets.

@wnqueiroz
Last active September 18, 2024 15:42
Show Gist options
  • 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:iron-alpine as builder
WORKDIR /usr/src/app
ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}
COPY package.json yarn.lock ./
RUN yarn global add @nestjs/cli@^10.0.0 \
&& yarn install --immutable
COPY . .
RUN yarn build
FROM node:iron-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 ["yarn", "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