If you're a fan of JavaScript, you'll love NestJs. NestJs is a NodeJs framework that emphasizes architecture. It modularizes the entire application into a service-oriented structure, making it easy to dockerize services.
Today, we will explore how to Dockerize a NestJs application for easy deployment. Docker simplifies server deployment.
At first, you have to create file named Dockerfile. This file is where the magic happens. Below is the code from the file:
FROM node:20
# Create app directory
WORKDIR /app
# A wildcard is used to ensure both package.json AND package-lock.json are copied
COPY package*.json /app/
# Install app dependencies
RUN npm install
# Bundle app source
COPY . /app/
# Creates a "dist" folder with the production build
RUN npm run build
# Expose the port on which the app will run
EXPOSE 3000
# Start the server using the production build
CMD ["npm", "run", "start"]A couple of points to note:
- We are using
node:20as the base image. This includes both the runtime and the Linux operating system, ensuring smooth operation. - If you are using Prisma for database connections, you need to add
RUN npx prisma generatebeforeRUN npm run build. It will generate necessary models.
The rest of the steps should be fairly straightforward.
Build the Docker Image:
Open a Terminal or PowerShell window, navigate to your project directory, and execute the following command to build the Docker image:
docker build -t your-app-nape .This command will create the Docker image tagged your-app-name, using the current directory as the build context.
Run Docker image
When the image is created, you can start a Docker container based on that image with the following command:
docker run --rm -p 3005:3000 your-app-nameThis will start a container from the image and map port 3005 of the container to port 3000 on your local machine. Now you should be able to access your NestJS API at http://localhost:3000. You can assign any port instead of 3005. But you must make sure that the selected port is not used by another process.


