ccweerasinghe1994 / how-to-dockerise-nestjs-application

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

Description

Nest framework TypeScript starter repository.

Installation

$ npm install

Running the app

# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod

Test

# unit tests
$ npm run test

# e2e tests
$ npm run test:e2e

# test coverage
$ npm run test:cov

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.

Stay in touch

License

Nest is MIT licensed.

To Dockerize the app

first create a dockerfile in the root directory of the project

touch Dockerfile

then create the docker ignore file

touch .dockerignore
FROM node:21

WORKDIR /user/src/app

COPY . .

RUN npm install

CMD [ "npm", "run","start:dev" ]
node_modules
test
.gitignore
.git
.prettierrc
Dockerfile
README.md 

let's build the image

docker build -t nestjs-docker .

Alt text

it will create an image with the name nestjs-docker

let's run the image

docker run nestjs-docker

Alt text

Alt text

let's make a request to the app

Alt text

we can see that the app is running on the docker container but we can't access it from the browser because it's running on the docker container

let's remove the running container

docker rm -f <container id>

then let's run the container again but this time we will map the port 3000 of the container to the port 3000 of the host machine

docker run -p 3000:3000 nestjs-docker

Alt text

now when we change the code in the app it will not be reflected in the container because we are not mounting the code to the container.

let's create a prod docker file

FROM node:21

WORKDIR /user/src/app

COPY . .

RUN npm install

RUN npm run build

RUN rm -rf .src

EXPOSE 3000

CMD [ "npm", "run","start:prod" ]
docker image build -t nestjs-prod -f Dockerfile.prod .

Alt text

let's run the image

docker run -p 3000:3000 nestjs-prod

About


Languages

Language:TypeScript 73.3%Language:JavaScript 22.9%Language:Dockerfile 3.8%