Docker 构建期间未在共享卷上复制文件

Docker is not copying file on a shared volume during build

我想将构建阶段创建的文件存储在我的本地机器上

我有这个 Dockerfile

FROM node:17-alpine as builder
WORKDIR '/app' 

COPY ./package.json ./   
RUN npm install
RUN npm i -g @angular/cli

COPY . .
RUN ng build foo --prod  
RUN touch test.txt #This is just for test

CMD ["ng", "serve"] #Just for let the container running

我还通过 docker compose

创建了一个共享卷
services:  
  client:
      build:
        dockerfile: Dockerfile.prod
        context: ./foo
      volumes:
        - /app/node_modules 
        - ./foo:/app

如果我将 shell 附加到 运行ning 容器和 运行 touch test.txt,该文件将在我的本地计算机上创建。 我不明白为什么文件没有在构建阶段创建...

如果我使用多阶段 Dockerfile,则会创建容器上的 dist 文件夹(只需将其添加到 Dockerfile),但我仍然无法在本地机器上看到它

FROM nginx
EXPOSE 80 
COPY --from=builder /app/dist/foo /usr/share/nginx/html

I can't understand why the files are not created on the building phase...

那是因为构建阶段不涉及卷安装。

安装卷只发生在创建容器时,而不是构建图像时。如果将卷映射到现有文件或目录,Docker“覆盖”映像的路径,很像传统的 linux 挂载。这意味着,在创建容器之前,您 image 拥有 /app/* pre-packaged 的所有内容,这就是您能够在多阶段构建中复制内容的原因。

但是,当您在 docker-compose 文件中使用 - ./foo:/app 配置定义卷时,容器 将不再有这些文件,并且相反,/app 文件夹将包含您的 ./foo 目录的当前内容。

如果您希望将映像的内容复制到已安装的卷中,您必须在 ENTRYPOINT 中执行此操作,因为它在容器实例化时以及在卷安装之后运行。