How to easily Dockerize your NestJs App

edgargonzalez525

Edgar Gonzalez

Posted on May 2, 2020

How to easily Dockerize your NestJs App

In this previous article I talked about how to create cron jobs with a NestJs application, now I'm going to take that same app and create a Docker script that we can use to deploy it on a production environment like AWS.

You can find the source code for this guide here.

I will assume you have some basic knowledge of how Docker works for this guide.

To Dockerize our app we are going to be using the following Docker file:

You can also find a gist for this Docker script here.

FROM node:12.15.0-alpine

# Create app directory
WORKDIR /usr/src/app

# Copy package files
COPY package*.json ./

# Install npm packages
RUN npm install

# Bundle app source
COPY . .

# Build our app for production
RUN npm run build

EXPOSE 3000
CMD [ "npm", "run", "start:prod" ]

I will go through each of the lines on the file and explain what they mean.

  • FROM node:12.15.0-alpine

In this line we are telling Docker to use as a base image the node:12.15.0-alpine, this node version was enough for the purpose of our app, I recommend always using a fixed version for your Docker scripts and not the latest o stable one, because when those versions change something can break on your app. So manual version updated are preferred by me.

  • WORKDIR /usr/src/app

This is the directory where we will copy and build our app.

  • COPY package*.json ./

A wildcard is used to ensure both package.json AND package-lock.json are copied where available (npm@5+)

  • RUN npm install

Here we will install all npm dependencies. It is recommended to use npm ci instead for prod environment, but I had some trouble to make that work properly with NestJs build command so I kept it simple with the usual npm install

  • COPY . .

Copy the rest of the app files. To avoid copying unwanted files, like the local dist folder or node_modules folder use a .gitignore file.

  • RUN npm run build

Execute the build command of our project, this will internally execute the NestJs build command and will generate the distribution files of our app.

  • EXPOSE 3000

This line is to expose port 3000 on the Docker instance that will be created. This port will depend on the port your app runs.

  • CMD [ "npm", "run", "start:prod" ]

Finally, execute our app and keep it running in the Docker instance.

To test the Docker script you can execute the following commands on the root of the project, remember to create the Docker and the .dockerignore files.

  • Build docker image docker build -t nestjs-cron .
  • Run docker instance on port 3010 of our local machine docker run --name nestjs-cron -p 3010:3000 nestjs-cron

As you saw it is very simple to dockerize our NestJs app. See you the next time.

💖 💪 🙅 🚩
edgargonzalez525
Edgar Gonzalez

Posted on May 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related