Access a docker network during build of docker-compose v2?

Summary

Having a docker-compose.yml file that builds an image like this:

services:
  my-service:
    build: 
      context: My.VS.AppFolder
    networks:
      - my-docker

networks:
  my-docker:
    external: true

the defined network is only avaliable in the ENTRYPOINT. But not during build. How can I access another container on the same network my-docker during build of the Dockerfile?

Use case: Fetching NuGet packages from private repo

Description of the use case

I have an ASP.NET Core MVC 2.1 web application. For a better seperation of concerns, I want to implement certain features in another seperated web app (e.g admin interface). To avoid copying shared things like app layout (Razor) or some helper utility classes, I created a shared project for those things.

So there are three projects now:

  • MyApp (The original application)
  • MyApp.Core (For shared things)
  • MyApp.Admin

Since MyApp.Core needs to be referenced from the other projects, I installed BaGet as simple NuGet hosting repo for my docker build environment. This container is internally referenced with it’s DNS name in nuget.config, created at solution level of MyApp (same on new MyApp.Admin but let’s focus on MyApp for simplicity).

The problems

In the Dockerfile of MyApp I’m doing now this:

RUN dotnet restore --configfile nuget.config

and need to access the dns name called baget on the my-docker network. Researchs show that this is only possible with at least version 3.4 of docker-compose, and seems still not officially documentated. But Docker removed several options from v2 in v3, for example ressource limits like mem_limits I’m using. From v3, they’re only avaliable using swarm, not on single nodes any more.

So I currently don’t see any solution than migrating to v3 and swarm, which would cause extra work and complexity without benefits other than this networking issue. My project isn’t that big that swarm is required.

Source: StackOverflow