DEV Community

innocent leonard
innocent leonard

Posted on

How to Dockerize nestJs app

Create a Dockerfile

###################
# BUILD FOR LOCAL DEVELOPMENT
###################

FROM node:16-alpine As development

WORKDIR /usr/src/app

COPY --chown=node:node package*.json ./

RUN npm install --force

COPY --chown=node:node . .

USER node

###################
# BUILD FOR PRODUCTION
###################

FROM node:16-alpine As build

WORKDIR /usr/src/app

COPY --chown=node:node package*.json ./

COPY --chown=node:node --from=development /usr/src/app/node_modules ./node_modules

COPY --chown=node:node . .

RUN npm run build

ENV NODE_ENV production

RUN npm i --force --only=production

RUN npm cache clean --force

USER node

###################
# PRODUCTION
###################

FROM node:16-alpine As production

COPY --chown=node:node --from=build /usr/src/app/node_modules ./node_modules

COPY --chown=node:node --from=build /usr/src/app/dist ./dist

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


Enter fullscreen mode Exit fullscreen mode

Here is How to build and run it

docker build -t {name} -f {dockerfile}
docker build -t {name} {Dockerfile location}

docker run -p {port}:{port} --env-file {.env} {Dockerimage}

Top comments (0)