Docker helps you package your NestJS app with everything it needs to run. This makes it easy to share and run your app anywhere without setup problems.
Docker containerization in NestJS
FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build EXPOSE 3000 CMD ["node", "dist/main.js"]
FROM sets the base image with Node.js installed.
WORKDIR sets the folder inside the container where commands run.
FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build EXPOSE 3000 CMD ["node", "dist/main.js"]
FROM node:18-alpine WORKDIR /usr/src/app COPY package.json yarn.lock ./ RUN yarn install --frozen-lockfile COPY . . RUN yarn build EXPOSE 3000 CMD ["node", "dist/main.js"]
npm ci for faster, clean installs in CI/CD pipelines.FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build EXPOSE 3000 CMD ["node", "dist/main.js"]
This Dockerfile creates a container for a NestJS app. It uses a small Node.js image, installs dependencies, builds the app, and runs it on port 3000.
FROM node:18-alpine # Set working directory WORKDIR /app # Copy package files and install dependencies COPY package*.json ./ RUN npm install # Copy all source files COPY . . # Build the NestJS app RUN npm run build # Expose port 3000 EXPOSE 3000 # Start the app CMD ["node", "dist/main.js"]
Remember to add a .dockerignore file to exclude node_modules and other unnecessary files to keep the image small.
Use docker build -t your-app-name . to build the image and docker run -p 3000:3000 your-app-name to run it.
Make sure your NestJS app listens on all network interfaces (0.0.0.0) inside the container, not just localhost.
Docker packages your NestJS app with everything it needs to run anywhere.
Use a Dockerfile to define how to build and run your app inside a container.
Containers help with easy sharing, deployment, and consistent environments.