Build service image by combining other service images

Hi everyone,
I am trying to build multiple web applications with the same docker-compose.yml and multiple Dockerfiles.
The two web applications are similar, but come from different repositories and the build process is slightly different.

Pseudo code

  # common base with env_file, platform, etc.
  _common: ...

  # builder will use builder.Dockerfile to 
  # generate a builder container with required tools
    extends: _common
      dockerfile: builder.Dockerfile   
    image: builder:XXX

  # Both code1 and code2 share the same dockerfile!

  # code1 will use code.Dockerfile to clone code1.git
    extends: _common
      dockerfile: code.Dockerfile
        GIT_REPO: code1.git
    image: code1:XXX

  # code2 will use same code.Dockerfile as code1 to clone code2.git
    extends: code1
        GIT_REPO: code2.git
    image: code2:XXX

  # app1 will use Dockerfile to build using images builder:XXX & code1:XXX
    extends: _common
      args: ...
    image: app1:XXX
      - builder
      - code1

  # app2 will use app2.Dockerfile to build using images builder:XXX & code2:XXX
    extends: _common
      args: ...
    image: app2:XXX
      - builder
      - code2

This sounds like a bit too much: create a common image (builder:XXX) and two different images with different source code (code1:XXX and code2:XXX) to be used to generate different application images (app1:XXX and app2:XXX respectively).
The thing is, I’d like to reuse as much as possible and if I put everything for just one app, e.g. app1, in a single Dockerfile (which works) it becomes huge and unreadable.

In short:

  1. The build environment is common;
  2. The source code is not, but can be retrieved in a similar way;
  3. Something tells me that depends_on is not meant to be used that way, but I would like to express that both the builder and the source code need to exist before building the web apps.

What am I doing wrong and how can I accomplish that?

depends_on in docker-compose.yml only runs the container when the other one is started and healthy.

For building images you use Dockerfile. You can build a base image and then use FROM in a different Dockerfile to use the base (doc)

Thank you very much.