Nodejs-找不到模块(Docker)



尝试在Docker中为我的nodejs应用程序测试多阶段构建,我一直在运行

internal/modules/cjs/loader.js:983
throw err;
^
Error: Cannot find module '/service/dist/server/server.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)
at Function.Module._load (internal/modules/cjs/loader.js:862:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}

我的Dockerfile

FROM mybaseimage as dev
WORKDIR /service
COPY src ./src
COPY package*.json ./
COPY yarn.lock ./
COPY tsconfig.json ./
# This is required to build native modules
# https://github.com/nodejs/docker-node/blob/main/docs/BestPractices.md#node-gyp-alpine
RUN apk add --no-cache 
g++ 
make 
py3-pip
# Not clearing the cache here saves us time in the next step
RUN yarn install 
&& yarn compile
# Re-use the dev container to create a production-ready node_modules dir
FROM dev AS build
WORKDIR /service
RUN rm -rf /service/node_modules
&& yarn install --production=true 
&& yarn cache clean
FROM mybaseimage AS prod
WORKDIR /service
COPY --from=build /service/dist/ .
COPY --from=build /service/node_modules/ .
# https://github.com/nodejs/docker-node/blob/main/docs/BestPractices.md#handling-kernel-signals
RUN apk add --no-cache dumb-init

EXPOSE 5678
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
CMD ["node", "dist/server/server.js"]

我的package.json

"serve": "node dist/server/server.js",
"start": "concurrently "docker-compose up" "yarn watch"",

我早期工作的Dockerfile是

FROM mybaseimage
#set working directory
WORKDIR /service
# Copy the needed files into the container
COPY src ./src
COPY package*.json ./
COPY yarn.lock ./
COPY tsconfig.json ./
RUN apk update
RUN apk add python3
RUN echo python3 --version
RUN yarn install
RUN yarn compile

EXPOSE 5678
ENTRYPOINT ["npm", "run", "serve"]

在最后阶段,您将COPY从构建阶段将distnode_modules树放到当前目录中。您需要在COPY的右侧明确说明子目录名称。

COPY --from=build /service/dist/ ./dist/
COPY --from=build /service/node_modules/ ./node_modules/

另请参阅COPY上的Dockerfile引用:由于COPY源是一个目录,因此该目录的内容将复制到目标,而不是目录本身。这与普通Unixcpmv命令不同。

您应该能够在构建的映像上运行调试容器来验证这一点;例如

docker run --rm your-image ls

应该显示构建dist树中的server子目录,以及所有单独安装的Node包,所有这些都直接在映像的/service目录中,而不是在子目录中。

最新更新