Conditional COPY/ADD in Dockerfile?

后端 未结 6 1082
暖寄归人
暖寄归人 2020-12-01 04:12

Inside of my Dockerfiles I would like to COPY a file into my image if it exists, the requirements.txt file for pip seems like a good candidate but how would this be achieved

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 04:46

    Tried the other ideas, but none met our requirement. The idea is to create base nginx image for child static web applications. For security, optimization, and standardization reasons, the base image must be able to RUN commands on directories added by child images. The base image does not control which directories are added by child images. Assumption is child images will COPY resources somewhere under COMMON_DEST_ROOT.

    This approach is a hack, but the idea is base image will support COPY instruction for 1 to N directories added by child image. ARG PLACEHOLDER_FILE and ENV UNPROVIDED_DEST are used to satisfy and requirements for any COPY instruction not needed.

    #
    # base-image:01
    #
    FROM nginx:1.17.3-alpine
    ENV UNPROVIDED_DEST=/unprovided
    ENV COMMON_DEST_ROOT=/usr/share/nginx/html
    ONBUILD ARG PLACEHOLDER_FILE
    ONBUILD ARG SRC_1
    ONBUILD ARG DEST_1
    ONBUILD ARG SRC_2
    ONBUILD ARG DEST_2
    ONBUILD ENV SRC_1=${SRC_1:-PLACEHOLDER_FILE}
    ONBUILD ENV DEST_1=${DEST_1:-${UNPROVIDED_DEST}}
    ONBUILD ENV SRC_2=${SRC_2:-PLACEHOLDER_FILE}
    ONBUILD ENV DEST_2=${DEST_2:-${UNPROVIDED_DEST}}
    
    ONBUILD COPY ${SRC_1} ${DEST_1}
    ONBUILD COPY ${SRC_2} ${DEST_2}
    
    ONBUILD RUN sh -x \
        #
        # perform operations on COMMON_DEST_ROOT
        #
        && chown -R limited:limited ${COMMON_DEST_ROOT} \
        #
        # remove the unprovided dest
        #
        && rm -rf ${UNPROVIDED_DEST}
    
    #
    # child image
    #
    ARG PLACEHOLDER_FILE=dummy_placeholder.txt
    ARG SRC_1=app/html
    ARG DEST_1=/usr/share/nginx/html/myapp
    FROM base-image:01
    

    This solution has obvious shortcomings like the dummy PLACEHOLDER_FILE and hard-coded number of COPY instructions that are supported. Also there is no way to get rid of the ENV variables that are used in the COPY instruction.

提交回复
热议问题