PNPM monorepo部署与Docker合成

h9vpoimq  于 2022-11-14  发布在  Docker
关注(0)|答案(1)|浏览(358)

我目前有一个monorepo,其结构如下:

.
├── services/
│   └── api/
│       ├── src/
│       │   └── ...
│       └── Dockerfile
├── apps/
│   └── frontend
├── packages/
│   └── ...
├── .npmrc
├── docker-compose.yaml
└── pnpm-lock.yaml

停靠文件包含以下命令:

FROM node:18-alpine As base

RUN npm i -g pnpm

FROM base AS dependencies

WORKDIR /usr/src/app

COPY package.json ../../pnpm-lock.yaml ./
COPY ../../.npmrc ./
RUN pnpm install --frozen-lockfile --prod
...

对于我在Docker文件中加载的API,使用了上下文为./services/api的Docker合成文件。当我尝试这样做时,它找不到父目录的文件,这是由于Docker的一些安全特性。我可以相应地更改上下文和命令,但这将加载API映像的整个代码库。这会减慢构建和部署的速度,我的问题是有没有其他方法来构建monorepo来支持pnpm和Docker?我找不到任何关于这个主题的资源。
此致

vfh0ocws

vfh0ocws1#

我现在实现了如下的Dockerfile。它是针对我的monorepo的,所以它可能没有什么用,但是如果有人遇到同样的问题,我还是想发布它:

FROM node:18.10.0-alpine As base

ARG SERVICE_PATH
ARG PACKAGE_NAME
ARG PNPM_VERSION

# Install package manager
RUN --mount=type=cache,id=pnpm-store,target=/root/.pnpm-store \
    npm i --global --no-update-notifier --no-fund pnpm@${PNPM_VERSION}

# Use the node user from the image (instead of the root user)
USER node

# Get all dependencies and install
FROM base AS dependencies

WORKDIR /usr/app

COPY --chown=node:node pnpm-lock.yaml pnpm-workspace.yaml package.json .npmrc ./
COPY --chown=node:node ${SERVICE_PATH}/package.json ./${SERVICE_PATH}/package.json

RUN --mount=type=cache,id=pnpm-store,target=/root/.pnpm-store \
    pnpm install --frozen-lockfile --filter ${PACKAGE_NAME}\
    | grep -v "cross-device link not permitted\|Falling back to copying packages from store"

# Build application using all dependencies, copy necessary files
FROM dependencies AS build

WORKDIR /usr/app/${SERVICE_PATH}

COPY --chown=node:node ${SERVICE_PATH} ./

ENV NODE_ENV production
RUN pnpm build
RUN rm -rf node_modules src \
    && pnpm -r exec -- rm -rf node_modules

# Use base image for correct context, get built files from build stage
# Install only production dependencies
FROM base AS deploy

WORKDIR /usr/app

ENV NODE_ENV production

COPY --chown=node:node --from=build /usr/app .
RUN --mount=type=cache,id=pnpm-store,target=/root/.pnpm-store \
    pnpm install --frozen-lockfile --filter ${PACKAGE_NAME} --prod \
    | grep -v "cross-device link not permitted\|Falling back to copying packages from store"

ENV EXEC_PATH=${SERVICE_PATH}/dist/main.js

CMD node ${EXEC_PATH}

我还按照bogdanoff的建议添加了一个.dockerignore,它看起来如下:

# Files
/**/*/.env
/**/*/.env.*
/**/*/README.md
/**/*/.git
/**/*/.gitignore
/**/*/npm-debug.log
/**/*/.dockerignore
/**/*/Dockerfile

# Directories
/**/*/node_modules
/**/*/test
/**/*/dist

相关问题