Sobes.tech
Junior — Middle

Why are multiple FROM commands used in a Dockerfile sometimes?

sobes.tech AI

Answer from AI

In a Dockerfile, multiple FROM commands are used to create a multi-stage build. This allows splitting the build process into several stages, each using its own base image.

Main reasons:

  • Size optimization of the final image: the application is built and compiled with necessary tools in the early stages, and only the required artifacts are copied into a minimal image at the final stage.
  • Environment separation: different images can be used for building and running, for example, an image with Python and build tools, and then a lightweight image with only the interpreter.

Example:

FROM python:3.9-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt
COPY . .
RUN python setup.py install

FROM python:3.9-alpine
COPY --from=builder /root/.local /root/.local
ENV PATH=/root/.local/bin:$PATH
CMD ["myapp"]

Thus, the final image contains only what is necessary to run, without build tools.

Why are multiple FROM commands used in a Dockerfile… - sobes.tech