Base image for multi-stage should be passed as build argument

Hello community!

Running Docker version 25.0.3, build 4debf41

I would need to use a Dockerfile with multi-stage, but the base image is passed by build-argument, as it requires the CI to generate the image (the image name is unique, based on commit, branch, etc). I can do it by adding ARG as the first thing in Dockerfile, but it’s not optimal, because in case I need to change an argument, I need to re-build everything again. So, I would like to know how to pass the build argument, but not triggering to build of the first image again.

Here is the project structure:

# .env
DOCKER_NAMESPACE=foobar
DOCKER_TAG=0.1.0
# compose.yml
services:
  foo:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        DOCKER_NAMESPACE: ${DOCKER_NAMESPACE}
        DOCKER_TAG: ${DOCKER_TAG}
    env_file:
      - .env
# Dockerfile
ARG DOCKER_NAMESPACE
ARG DOCKER_TAG

FROM ubuntu:20.04 as builder

RUN echo "Building your application and more"

FROM ${DOCKER_NAMESPACE}/deployer:${DOCKER_TAG} as deploy

# Copy built application from the builder stage
COPY --from=builder /app /app

So I run docker compose build foo.

The follow example works, but is not smart enough to skip builder in case I change any argument. As you can see, both arguments are only related to deploy, so I would like to be able to build only deploy, in case changing arguments, but using the same build command. Is it possible? What alternative should I use?

Right now, if move ARG just before FROM ${DOCKER_NAMESPACE}/deployer:${DOCKER_TAG} as deploy is does not work, Docker returns an error as both are empty.