Home > other >  Reducing the Docker image size with multibuild
Reducing the Docker image size with multibuild

Time:10-15

I have a Python app, in which I would like to reduce the image size by removing the git, if possible. This is the Dockerfile:

FROM python:3.8-slim-buster

ARG GITHUB_TOKEN

RUN apt-get update && \ 
    apt-get upgrade -y && \
    apt-get install -y git gcc

WORKDIR /app
COPY . .

RUN git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf "https://github.com/"
RUN pip install -r requirements.txt

EXPOSE 3000

CMD ["./start.sh"]

I have tried the following:

FROM python:3.8-slim-buster AS base

ARG GITHUB_TOKEN

RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y git gcc

WORKDIR /app


FROM base
COPY . .
RUN git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf "https://github.com/"
RUN pip install -r requirements.txt

EXPOSE 3000

CMD ["./start.sh"]

Image is built without error, but the size remains the same in both versions. How can I go about this?

CodePudding user response:

With multi-stage build, you are splitting your building and running phases. The main benefits we achieve in the running stage is to avoid installing compilation tools (less image size) and not to accumulate too many intermediate layers (less image size again).

So, in the first stage, build it:

FROM python:3.8-slim-buster AS builder

ARG GITHUB_TOKEN

RUN apt-get update && \ 
    apt-get upgrade -y && \
    apt-get install -y git gcc

WORKDIR /app
COPY . .

RUN git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf "https://github.com/"
RUN pip install -r requirements.txt

And, for the second stage, run it:

FROM python:3.8-slim-buster
COPY --from=builder /app /app/

EXPOSE 3000
CMD ["./start.sh"]

Final result:

FROM python:3.8-slim-buster AS builder

ARG GITHUB_TOKEN

RUN apt-get update && \ 
    apt-get upgrade -y && \
    apt-get install -y git gcc

WORKDIR /app
COPY . .

RUN git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf "https://github.com/"
RUN pip install -r requirements.txt


FROM python:3.8-slim-buster
COPY --from=builder /app /app/

EXPOSE 3000
CMD ["./start.sh"]

Your faults were:

  • FROM base "base" was a alias for the first stage and should not be used as base image, but with COPY commands.
  • In the running stage, COPY without --from argument will copy files from the main context (filesystem). We want to copy the compiled artifacts generated in the previous stage, using --from argument.
  • Related