'How to prevent docker compose building the same image multiple times for docker compose V2?

This question builds off of the question asked here: How to prevent docker-compose building the same image multiple times?

In version 1 of docker compose, if you have multiple services which depend on the same dockerfile, you can prevent the dockerfile from being built twice by specifying the build tag once and referring the the image in dependent services:

version: '2'
services:

  abc:
    image: myimage
    command: abc
    build:
      context: .
      dockerfile: Dockerfile

  xyz:
    image: myimage
    depends_on:
      - abc
    command: xyz

The above code runs properly after disabling version 2 of docker-compose:

docker-compose disable-v2
docker-compose up

However if you run docker-compose v2.3.3, it gives the following error:

[+] Running 0/2
 ⠿ abc Error                                                                                                                                                                                                                                                                                                       1.3s
 ⠿ xyz Error                                                                                                                                                                                                                                                                                                       1.3s
Error response from daemon: pull access denied for myimage, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

What is the proper way to have multiple services use one dockerfile in docker-compose version 2?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source