The Last Dockerfile You Need for NestJS

In this article

  •  We’ll write a docker multi-stage build together.
  •  We’ll discover how to use the docker file in development and production.
  •  We’ll apply some of the best practices recommended by the Docker team.

Let’s go.

First, let’s think about the use cases to design the docker build:

  • To install all the dependencies to support the local dev server.
  • To run a production server with an optimized bundle.

In order to cover both of the use cases, we’ll use Docker’s multi-stage builds and split the build into 3 stages:

  • dev: to simply install all the dependencies.
  • build: to compile a production build with optimized bundle size.
  • prod: to serve the production build.

The Docker Multi-stage Build

The “dev” Stage

It’s fairly straightforward. All we need to do is to install npm dependencies and apply some of the best practices:

  • We’ll use “node:alpine” as the based image to produce minimal image size.
  • We’ll install missing shared libraries from node:alpine.
  • We’ll assign a non-root user to Docker to limit its privileges
  • We’ll set the environment to “development”.
  • We’ll install the dependencies based on yarn lock file to achieve consistent installation across machines.

Read More