Failed to solve: failed to parse stage name "any-docker-image:": invalid reference format

TLTR: How can i pass an argument in docker compose v2?

I am migrating vom docker compose v1 to v2. In v1 this one was working (please keep in mind, this is just a minimal example):

script.sh:

#!/bin/bash

c_version=3
export CONTAINER_VERSION="$c_version"
docker-compose pull && docker-compose up --build -d

docker-compose.yml:

version: '3'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        - CONTAINER_VERSION=${CONTAINER_VERSION}

Dockerfile:

ARG CONTAINER_VERSION
FROM any-docker-image:${CONTAINER_VERSION}

RUN apt-get update

So when i run ./script.sh, the docker-compose.yml builds the stuff inside Dockerfile and pass CONTAINER_VERSION as an argument to docker-compose.yml and the Dockerfile. I’ll get any-docker-image:3. This was working.

Now i migrate to docker compose v2 and running this leads to:

failed to solve: failed to parse stage name “any-docker-image:”: invalid reference format

So obviously the variable CONTAINER_VERSION was not pass correctly.
I recognized that in v2 you can add the build section the docker-compose.yml like this:

build: ./app

Has the syntax changed in v2 in order to pass an argument from the docker-compose.yml (or compose.yml how it’s called in v2)? In v1 i could use

    build:
      context: .
      dockerfile: Dockerfile
      args:
        - CONTAINER_VERSION=${CONTAINER_VERSION}

How can i fix this?

It was always the case and not introduced in v2.

If you had an invalid syntax, you couldn’t run compose at all.

Is this a minimal example script which produces the error message when you replace docker-compose with docker compose? If not, please share one which can reproduce the issue. I don’t see anything in the script that wouldn’t work with v2, which is actually a compose that understand all old compose yaml syntax versions, so the version number is ignored in the yaml.