You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用docker buildx build复制容器内文件到本地失败求助

Docker Buildx导出整个镜像文件系统而非指定文件的解决方法

问题背景

我有一个多阶段构建的Dockerfile如下:

FROM archlinux:latest AS builder

RUN pacman-key --init
RUN pacman -Syu --noconfirm
RUN pacman -S --noconfirm gcc cmake git make zip curl pkgconf autoconf gettext automake libtool zlib
WORKDIR /home
RUN git clone --recurse-submodules https://github.com/aws/aws-sdk-cpp.git
RUN cd aws-sdk-cpp && \
    mkdir -p build && \
    cd build && \
    cmake .. -DBUILD_ONLY="core" -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF -DCUSTOM_MEMORY_MANAGEMENT=OFF -DCMAKE_INSTALL_PREFIX=/usr && \
    make -j8 && \
    make install
WORKDIR /home
RUN git clone https://github.com/awslabs/aws-lambda-cpp.git
RUN cd aws-lambda-cpp && \
    mkdir -p build && \
    cd build && \
    cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr && \
    make -j8 && \
    make install
WORKDIR /home
RUN git clone https://github.com/sekrit-twc/zimg
RUN cd zimg && \
    git submodule init graphengine && \
    git submodule update && \
    ./autogen.sh && \
    ./configure --prefix=/usr && \
    make -j8 && \
    make install

WORKDIR /opt
COPY . .
RUN cmake . -DCMAKE_BUILD_TYPE=Release -DLOG_VERBOSITY=3
RUN make
RUN make aws-lambda-package-zimg-api

FROM archlinux:latest AS api
WORKDIR /opt
COPY --from=builder /opt/zimg-api.zip .
RUN cp /opt/zimg-api.zip /home/zimg-api.zip

我尝试执行以下命令将容器内的/home/zimg-api.zip复制到本地:

docker buildx build -f Dockerfile -t zimg-api:0.0.10 --target api --output type=local,dest=$(pwd) .

但实际导出了整个ArchLinux镜像的文件系统,而非我需要的单个zip文件。

问题分析

docker buildx build的type=local输出模式默认会将目标构建阶段的完整文件系统复制到指定的本地目录,这就是你得到整个镜像内容的原因。

解决方案

方案1:直接从builder阶段导出目标文件(推荐)

你的api阶段仅做了文件复制操作,完全可以跳过该阶段,直接从builder阶段导出生成好的zimg-api.zip。修改命令如下:

docker buildx build -f Dockerfile --target builder --output type=local,dest=$(pwd),source=/opt/zimg-api.zip .

该命令会直接将builder阶段中/opt/zimg-api.zip文件导出到当前本地目录。

方案2:修改api阶段为仅包含目标文件

如果需要保留api阶段,可将该阶段的基础镜像改为空镜像(scratch),让镜像中只包含需要的zip文件:

FROM scratch AS api
COPY --from=builder /opt/zimg-api.zip /zimg-api.zip

修改后执行你原来的buildx命令,此时导出的就只有zimg-api.zip文件了。

方案3:使用docker cp复制(备选)

先构建出api镜像,再通过临时容器将文件复制到本地:

# 构建api镜像
docker build -f Dockerfile -t zimg-api:0.0.10 --target api .
# 启动临时容器并复制文件到当前目录
docker run --rm -v $(pwd):/host zimg-api:0.0.10 cp /home/zimg-api.zip /host/

内容的提问来源于stack exchange,提问作者aculnaig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 13:17:38