如何在NestjS应用中使用Docker

r6l8ljro  于 2023-06-21  发布在  Docker
关注(0)|答案(2)|浏览(111)

我有一个NestJS项目,有很多应用程序,结构如下:

my-project:
-- apps;
--- app-one
---- src
---- tsconfig.app.json
--- app-two
---- src
---- tsconfig.app.json
-- libs
-- package.json
-- etc...

我在一个项目中有两个应用程序:app-oneapp-two,如何使用docker部署app-oneapp-two。当我有一个应用程序,我知道如何做到这一点,我将创建Dockerfilepackage.json目录和构建/运行,但如何做到这一点与嵌套的应用程序?
谢谢你的帮助

nimxete2

nimxete21#

你可以在根目录下有多个不同文件名的Dockerfile。

my-project:
-- apps;
--- app-one
---- src
---- tsconfig.app.json
--- app-two
---- src
---- tsconfig.app.json
-- libs
-- package.json
-- Dockerfile.app-one
-- Dockerfile.app-two

对于Dockerfiles,您只需要运行自定义脚本来构建指定的应用程序
Dockerfile.app-one

FROM node:12.17-alpine as builder

WORKDIR /build
COPY package.json yarn.lock ./
RUN yarn

COPY . .
RUN  yarn build:app-one

EXPOSE 3000

CMD [ "yarn", "start:app-one"]

package.json

"scripts": {
  "build:app-one": "nest build app-one",
  "build:app-two": "nest build app-two",
  "start:app-one": "nest start app-one",
  "start:app-two": "nest start app-two",
}

nest-cli.json

{
  "projects": {
    "app-one": {
      "type": "application",
      "root": "apps/app-one",
      "entryFile": "main",
      "sourceRoot": "apps/app-one/src",
      "compilerOptions": {
        "tsConfigPath": "apps/app-one/tsconfig.app.json",
        "assets": []
      }
    },
    "app-two": {
      "type": "application",
      "root": "apps/app-two",
      "entryFile": "main",
      "sourceRoot": "apps/app-two/src",
      "compilerOptions": {
        "tsConfigPath": "apps/app-two/tsconfig.app.json",
        "assets": []
      }
    },
  }
}

然后,在CI/CD中的构建/部署任务中指定文件名
.gitlab-ci.yml

image: docker:git

services:
  - docker:dind

stages:
  - build

build-app-one:
  stage: build
  script:
    - docker build . -f Dockerfile.app-one

build-app-two:
  stage: build
  script:
    - docker build . -f Dockerfile.app-two

如果您需要更多信息,请阅读有关monorepo architecture in NestJS的文档

3yhwsihp

3yhwsihp2#

所有应用程序都可以使用一个Dockerfile。

FROM node:18-alpine As build

ARG SERVICE_NAME

WORKDIR /usr/src/app

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

RUN yarn install --frozen-lockfile

COPY --chown=node:node . .

RUN yarn build $SERVICE_NAME

ENV NODE_ENV production
RUN yarn install --production --frozen-lockfile

USER node

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

FROM node:18-alpine As production

ARG SERVICE_NAME
ENV NODE_ENV production

WORKDIR /usr/src/app
COPY --chown=node:node --from=build /usr/src/app/node_modules ./node_modules
COPY --chown=node:node --from=build /usr/src/app/dist/apps/${SERVICE_NAME}/* .

USER node

CMD ["node", "main.js"]

然后docker build命令看起来像这样:

docker build -t <tag-name> --build-arg SERVICE_NAME=<nestjs-app-name> .

相关问题