Nestjs docker - Run nestjs in container

In this article we will convert our nestjs app into docker image with multi stage build.
Creating the Dockerfile
create a dockerfile and .dockerignore file in the root directory of your project
touch Dockerfile
touch .dockerignore

Add the following code in the .dockerignore file to prevent these files to be added in the docker build process
Dockerfile
.dockerignore
node_modules
npm-debug.log
dist
Writing Multistage Build:
Add the following code in the dockerfile to create the multistage docker build
# Base Image
FROM node:16-alpine AS development
WORKDIR /opt
COPY package*.json ./
# npm clean install
RUN npm ci
COPY . .
RUN npm run build
# production docker build
FROM node:16-alpine AS production
ENV NODE_ENV=production
WORKDIR /opt
COPY package*.json ./
# install only production node modules
RUN npm ci --omit=dev
COPY . .
COPY --from=development /opt/dist ./dist
EXPOSE 3000
CMD ["node" , "dist/main"]
Here we are using node:16-alpine as a base image so the build version will less than 512 MB in size since the base image size will 116 MB only.
Once you have completed above steps you can run the below command to create the nestjs docker image
docker build . -t <image name>
To start the nestjs app as a container, run the below command
docker run -p 3000:3000 <image-name>
Troubleshooting:
if you face any typescript error, while running the npm run build step, change the allowJs to false in tsconfig.json file.
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,
"allowJs": false
}
}