From 0ca623329a986bace4303d2978ee40c1223709f0 Mon Sep 17 00:00:00 2001 From: Michael Manganiello Date: Wed, 22 Feb 2023 10:26:02 -0300 Subject: [PATCH] Reduce Docker image size by only copying pip installed dependencies Currently, the multi-stage Docker build makes the `release` stage inherit from `dependencies`, which will include any files created by the `pip install` process in the final image. By using `pip install --user` to make dependencies be installed in `~/.local`, we can only copy those files into the final image, reducing the image size: ``` cloudflare-ddns-fix-applied latest 68427bd7c88d 3 minutes ago 54.6MB cloudflare-ddns-master latest 2675320b651d 8 minutes ago 65.9MB ``` A good resource going deeper on how this approach works can be found at https://pythonspeed.com/articles/multi-stage-docker-python/, solution 1. --- Dockerfile | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Dockerfile b/Dockerfile index c0b4891..a66379b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,12 +6,13 @@ FROM python:alpine AS base FROM base AS dependencies # install dependencies COPY requirements.txt . -RUN pip install -r requirements.txt - +RUN pip install --user -r requirements.txt + # # ---- Release ---- -FROM dependencies AS release -# copy project source file(s) +FROM base AS release +# copy installed dependencies and project source file(s) WORKDIR / +COPY --from=dependencies /root/.local /root/.local COPY cloudflare-ddns.py . -CMD ["python", "-u", "/cloudflare-ddns.py", "--repeat"] \ No newline at end of file +CMD ["python", "-u", "/cloudflare-ddns.py", "--repeat"]