The Last Dockerfile You Need for NestJS

<h1>In this article</h1> <ul> <li>&nbsp;We&rsquo;ll write a docker multi-stage build together.</li> <li>&nbsp;We&rsquo;ll discover how to use the docker file in development and production.</li> <li>&nbsp;We&rsquo;ll apply some of the best practices recommended by the Docker team.</li> </ul> <p>Let&rsquo;s go.</p> <p>First, let&rsquo;s think about the use cases to design the docker build:</p> <ul> <li>To install all the dependencies to support the local dev server.</li> <li>To run a production server with an optimized bundle.</li> </ul> <p>In order to cover both of the use cases, we&rsquo;ll use Docker&rsquo;s&nbsp;<a href="https://docs.docker.com/build/building/multi-stage/" rel="noopener ugc nofollow" target="_blank">multi-stage builds</a>&nbsp;and split the build into 3 stages:</p> <ul> <li><strong>dev</strong>: to simply install all the dependencies.</li> <li><strong>build</strong>: to compile a production build with optimized bundle size.</li> <li><strong>prod</strong>: to serve the production build.</li> </ul> <h1>The Docker Multi-stage Build</h1> <h1>The &ldquo;dev&rdquo; Stage</h1> <p>It&rsquo;s fairly straightforward. All we need to do is to install npm dependencies and apply some of the&nbsp;best practices:</p> <ul> <li>We&rsquo;ll use &ldquo;node:alpine&rdquo; as the based image to produce minimal image size.</li> <li>We&rsquo;ll install&nbsp;missing shared libraries&nbsp;from node:alpine.</li> <li>We&rsquo;ll assign a&nbsp;non-root user&nbsp;to Docker to limit its privileges</li> <li>We&rsquo;ll set the environment to &ldquo;development&rdquo;.</li> <li>We&rsquo;ll install the dependencies based on&nbsp;yarn lock file&nbsp;to achieve consistent installation across machines.</li> </ul> <p><a href="https://levelup.gitconnected.com/the-last-dockerfile-you-need-for-nestjs-76cbfe1edf48">Read More</a>&nbsp;</p>