If BuildKit sees that a stage depends on other stages which do not depend on each other, then it will run those stages in parallel (assuming there are enough threads/CPUs available, anyway). Here's an example:
# syntax=docker/dockerfile:1.4
FROM alpine as s1
RUN echo Stage s1 building, time is `date` >/s1.txt && sleep 10
FROM alpine as s2
RUN echo Stage s2 building, time is `date` >/s2.txt && sleep 10
FROM alpine as s3
RUN echo Stage s3 building, time is `date` >/s3.txt && sleep 10
FROM s3 AS final-stage
COPY --from=s1 /s1.txt /
COPY --from=s2 /s2.txt /
ENTRYPOINT cat /s*.txt
If you build this with docker build .
(which implicitly builds the last stage in the Dockerfile), stages s1
, s2
and s3
will automatically run in parallel (again, assuming you have the system resources, but it's what happens on my pretty old computer). The entire build finishes in little over 10 seconds...
$ docker build .
[+] Building 12.6s (14/14) FINISHED
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 419B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> resolve image config for docker.io/docker/dockerfile:1.4 1.6s
=> CACHED docker-image://docker.io/docker/dockerfile:1.4@sha256:9ba7531bd80fb0a858632727cf7a112fbfd19b17e94c4e84ced81e24ef1a0dbc 0.0s
=> [internal] load build definition from Dockerfile 0.0s
=> [internal] load .dockerignore 0.0s
=> [internal] load metadata for docker.io/library/alpine:latest 0.0s
=> CACHED [s2 1/2] FROM docker.io/library/alpine 0.0s
=> [s1 2/2] RUN echo Stage s1 building, time is `date` >/s1.txt && sleep 10 10.4s
=> [s3 2/2] RUN echo Stage s3 building, time is `date` >/s3.txt && sleep 10 10.5s
=> [s2 2/2] RUN echo Stage s2 building, time is `date` >/s2.txt && sleep 10 10.4s
=> [final-stage 1/2] COPY --from=s1 /s1.txt / 0.0s
=> [final-stage 2/2] COPY --from=s2 /s2.txt / 0.0s
=> exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:3f76475f4bab8aa773a7b4daf1403cbd269fa964b7133f81800e1359eae08d60 0.0s
Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them
... and if we run the image, we can see the stages did indeed run at the same time:
$ docker run --rm sha256:3f76475f4bab8aa773a7b4daf1403cbd269fa964b7133f81800e1359eae08d60
Stage s1 building, time is Wed Jan 25 18:52:50 UTC 2023
Stage s2 building, time is Wed Jan 25 18:52:50 UTC 2023
Stage s3 building, time is Wed Jan 25 18:52:50 UTC 2023
So to answer your question, you could split stage3
into two stages, where one does the actual work, and the other just copies stuff from other stages:
FROM yetAnotherImg As stage3-intermediate
# more work
FROM stage3-intermediate AS stage3
COPY --from=stage2 ... # stage2 and stage3-intermediate will run in parallel