读取Dockerfile中的文件路径列表并将每个文件从一个构建阶段复制到另一个

时间:2019-11-14 18:14:07

标签: bash docker

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

问题: 因为第一阶段通过apk-add安装软件包,并且还从git克隆并安装软件包,所以最后一个可执行文件的依赖关系显示在文件系统内的各个位置(主要是/ usr / lib,/ usr / local / lib,/ lib)。为了解决这个问题,在构建阶段,我用一些正则表达式在主可执行文件上运行“ ldd”命令,该正则表达式将所有.so库路径通过管道传输到文本文件中。然后,我将此文本文件以及主要可执行文件复制到第二阶段,在该阶段我想读取文本文件的内容,并将从构建阶段开始的每一行(库路径)复制到第二阶段。但是,鉴于Dockerfile在没有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"]

0 个答案:

没有答案