---
# System prepended metadata

title: NestJS Momorepo
tags: [nestjs]

---

# 建立專案
```shell=
nest new webrepos
cd webrepos
nest g app svc01
nest g app svc02
nest g library common
```

# 修改nest-cli.json
* 移除webrepos區塊
* 設定啟動專案

```json
{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "apps/svc01/src",
  "monorepo": true,
  "root": "apps/svc01",
  "compilerOptions": {
    "webpack": true,
    "tsConfigPath": "apps/svc01/tsconfig.app.json"
  },
  "projects": {
    "svc01": {
      "type": "application",
      "root": "apps/svc01",
      "entryFile": "main",
      "sourceRoot": "apps/svc01/src",
      "compilerOptions": {
        "tsConfigPath": "apps/svc01/tsconfig.app.json"
      }
    },
    "svc02": {
      "type": "application",
      "root": "apps/svc02",
      "entryFile": "main",
      "sourceRoot": "apps/svc02/src",
      "compilerOptions": {
        "tsConfigPath": "apps/svc02/tsconfig.app.json"
      }
    },
    "common": {
      "type": "library",
      "root": "libs/common",
      "entryFile": "index",
      "sourceRoot": "libs/common/src",
      "compilerOptions": {
        "tsConfigPath": "libs/common/tsconfig.lib.json"
      }
    }
  }
}

```
# 執行命令
```shell
npm run start:dev
npm run start:dev svc02

npm run build
npm run build svc02

node dist/apps/svc01/main
node dist/apps/svc02/main
```

# 加入Dockerfile
```dockerfile
FROM node:lts-alpine as build
WORKDIR /app
COPY package*.json .
RUN npm install
COPY . .
RUN npm run build

FROM node:lts-alpine as base
WORKDIR /app
COPY package.json .
RUN npm install --only=production
COPY --from=build /app/dist /app/dist
CMD ["node", "dist/apps/svc01/main"]
```

## 加入docker-compose
* docker-compose up --build

```yaml
version: '3.5'

services:
  svc01:
    image: svc01:local
    build:
      context: .
      dockerfile: ./Dockerfile
      target: build
    env_file:
      - ./apps/svc01/.env
    command: npm run start:dev svc01
    volumes:
      - .:/app
      - /app/node_modules

  svc02:
    image: svc02:local
    build:
      context: .
      dockerfile: ./Dockerfile
      target: build
    env_file:
      - ./apps/svc01/.env
    command: npm run start:dev svc02
    volumes:
      - .:/app
      - /app/node_modules

```