Last active
September 18, 2024 15:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 efficientDockerfile
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