Conditional COPY/ADD in Dockerfile?

后端 未结 6 1080
暖寄归人
暖寄归人 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:51

    Copy all files to a throwaway dir, hand pick the one you want, discard the rest.

    COPY . /throwaway
    RUN cp /throwaway/requirements.txt . || echo 'requirements.txt does not exist'
    RUN rm -rf /throwaway
    

    You can achieve something similar using build stages, which relies on the same solution, using cp to conditionally copy. By using a build stage, your final image will not include all the content from the initial COPY.

    FROM alpine as copy_stage
    COPY . .
    RUN mkdir /dir_for_maybe_requirements_file
    RUN cp requirements.txt /dir_for_maybe_requirements_file &>- || true
    
    FROM alpine
    # Must copy a file which exists, so copy a directory with maybe one file
    COPY --from=copy_stage /dir_for_maybe_requirements_file /
    RUN cp /dir_for_maybe_requirements_file/* . &>- || true
    CMD sh
    

提交回复
热议问题