Nedim Bajric
Nedim Bajric

Reputation: 31

How to dockerize nestjs app in nx monorepo

I am working on Nx monorepo with several projects inside. Now, I need to dockerize my nestjs app.

I am not sure how to create Docker file inside the 'backend' folder ( my nestjs app ), to be executed as expected.

Normally I am starting the app using this command: yarn run nx backend:serve But this doesn't work on the docker. It says that command nx backend:serve is not found.

My dockerfile looks like this:

FROM node:20.9.0-alpine3.18

WORKDIR /src

RUN npm add --global nx@latest

# Copy package.json and package-lock.json from the root of the build context
COPY package*.json ./

# Install dependencies
RUN yarn  

# Expose the port the app runs on
EXPOSE 3000

# Command to run the application
CMD [ "yarn", "run","nx backend:serve" ]

Upvotes: 2

Views: 359

Answers (1)

Kien Pham
Kien Pham

Reputation: 117

I'm currently working on NX Nestjs, here is my Dockerfile. This may not the best but it works. I use pm2 to start the app.

Remember to change yourNestAppName with your app name and port as you want.

Dockerfile (/apps/app-name/Dockerfile)

    # build
    FROM node:lts-alpine AS builder
    
    WORKDIR /usr/src/app
    COPY package*.json ./
    
    RUN npm install --only=development --silent
    
    COPY . .
    
    RUN npx nx run yourNestAppName:build:production
    
    # Production image
    FROM node:lts-alpine
    ENV NODE_ENV production
    
    WORKDIR /usr/src/app
    COPY package*.json ./
    
    RUN npm install -g pm2@latest
    RUN npm install --only=production --silent
    
    COPY --from=builder /usr/src/app/dist/apps/yourNestAppName ./build
    
    ENTRYPOINT ["pm2-runtime","build/main.js"]

docker-compose.yml (in the folder)

    services:
      api:
        container_name: api
        restart: always
        ports:
          - "3001:3001"
        build:
          context: .
          dockerfile: ./apps/api/Dockerfile
        environment:
          - NODE_ENV=production
          - PORT=3001
        expose:
          - 3001

Upvotes: 0

Related Questions