Copy file out of docker image during docker build

I have a simply Dockerfile to build python requirements into a zip file to be uploaded to AWS Lambda.

FROM amazonlinux:2.0.20221004.0

RUN yum install -y python37 && \
    yum install -y python3-pip && \
    yum install -y zip && \
    yum clean all

RUN python3.7 -m pip install --upgrade pip && \
    python3.7 -m pip install virtualenv

COPY aws_requirements.txt .

RUN pip install -r aws_requirements.txt -t ./python
RUN zip -r python.zip ./py

Is there a way to copy the python.zip out of the image to the host during the dockerfile?

>Solution :

With buildkit, you can output the result to a directory on the host instead of pushing to a registry. So you can put the zip file in a scratch image and then output that:

FROM amazonlinux:2.0.20221004.0 as build

RUN yum install -y python37 && \
    yum install -y python3-pip && \
    yum install -y zip && \
    yum clean all

RUN python3.7 -m pip install --upgrade pip && \
    python3.7 -m pip install virtualenv

COPY aws_requirements.txt .

RUN pip install -r aws_requirements.txt -t ./python
RUN zip -r /python.zip ./py

FROM scratch as artifact
COPY --from=build /python.zip /python.zip

Then running:

docker build --output type=local,dest=out .

Will create a out/python.zip file.

Leave a Reply