Deploying a NestJS application to production can be streamlined using Docker. This tutorial provides a step-by-step guide to containerize your NestJS app, ensuring consistency across environments and simplifying deployment workflows.

Prerequisites

  • Node.js and npm installed on your machine
  • Docker installed and running
  • Basic knowledge of NestJS framework
  • Access to a terminal or command prompt

Step 1: Prepare Your NestJS Application

Ensure your NestJS application is ready for production. Run the following commands to build your app:

npm run build

This generates a dist folder containing the compiled code.

Step 2: Create a Dockerfile

In your project root, create a file named Dockerfile with the following content:

FROM node:18-alpine

WORKDIR /app

COPY package*.json ./

RUN npm install --production

COPY . .

RUN npm run build

EXPOSE 3000

CMD ["node", "dist/main.js"]

Step 3: Build the Docker Image

Open your terminal, navigate to your project directory, and run:

docker build -t nestjs-app:latest .

Step 4: Run the Docker Container

Start a container from your image with the following command:

docker run -d -p 80:3000 --name nestjs-container nestjs-app:latest

Step 5: Verify Deployment

Open your browser and navigate to http://localhost. You should see your NestJS application running.

Additional Tips

  • Use docker-compose for multi-container setups
  • Optimize your Dockerfile for smaller images using multi-stage builds
  • Implement environment variables for configuration
  • Secure your Docker deployment for production environments

Containerizing your NestJS app with Docker simplifies deployment and ensures consistency across environments. Follow these steps to deploy confidently to production.