首页 > 解决方案 > 读取 Dockerfile 中的文件路径列表并将每个文件从一个构建阶段复制到另一个构建阶段

问题描述

概述:我目前正在尝试在 Docker 中对我的 C++ 程序进行 dockerize。我正在使用多阶段构建结构,其中第一阶段负责下载所有必需的依赖项,然后构建/安装它们。然后第二阶段(也是最后阶段)从第一阶段复制所需的可执行文件和共享库以创建最终映像。还应该注意的是,我需要使用这种多阶段结构,因为构建器阶段使用私有 ssh 密钥来克隆私有 git 存储库,因此需要从最终映像中清除。

问题:因为第一阶段通过 apk-add 安装包,并且还从 git 克隆和安装包,所以我的最终可执行文件的依赖项显示在文件系统中的不同位置(主要是 /usr/lib、/usr/local/lib、/lib )。为了解决这个问题,在构建阶段,我在我的主可执行文件上运行了一个“ldd”命令,其中包含一些将所有 .so 库路径通过管道传输到文本文件中的正则表达式。然后我将此文本文件以及主可执行文件复制到第二阶段,我想在第二阶段读取文本文件的内容并将每一行(库路径)从构建阶段复制到第二阶段。但是,鉴于 Dockerfiles 不支持没有 bash 脚本的循环,所以我看不到可以将库从构建阶段复制到最终阶段的方法。我在下面附上了一些代码。感谢您的帮助!

#
# ... instructions that install libraries via apk-add and from source
#


# Generate a list of all of the libaries our bin directory depends on and pipe it into a text file
# so our later build stages can copy the absolute minimum neccessary libraries
RUN find /root/$PROJ_NAME/bin -type f -perm /a+x -exec ldd {} \; \
    | grep so \
    | sed -e '/^[^\t]/ d' \
    | sed -e 's/\t//' \
    | sed -e 's/.*=..//' \
    | sed -e 's/ (0.*)//' \
    | sort \
    | uniq  \
    >> /root/$PROJ_NAME/LIBRARY_DEPS.txt


#
# STAGE 2: Build fetched repos and install apk packages
#
FROM alpine:edge




ARG PROJ_NAME
ARG USER_ID
ARG GROUP_ID


# Copy over our main project directory from STAGE 1, which also includes
# the ldd paths of our main executable
COPY --from=builder /root/$PROJ_NAME /root/$PROJ_NAME

# PROBLEM: This is where I am stuck...would like to copy all of the libraries
# whose paths are specified in LIBRARY_DEPS.txt from the builder stage to the current stage
COPY --from=builder (cat /root/$PROJ_NAME/LIBRARY_DEPS.txt) ./

ENTRYPOINT ["./MainExecutable"]

标签: bashdocker

解决方案


推荐阅读