Arash
Arash

Reputation: 4260

An issue with resolving directory names when building a docker container for an asp.net core 3.1 web app

Visual Studio 2019 generates a docker file whose COPY statement looks like the following due to the way that the application's folders are structured:

FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /src
COPY ["MyWebApp/MyWebApp.csproj", "MyWebApp/"]
COPY ["../../core/Logic/Logic.csproj", "../../core/Logic/"]
COPY ["../../core/Models/Models.csproj", "../../core/Models/"]
RUN dotnet restore "MyWebApp/MyWebApp.csproj"
COPY . .
WORKDIR "/src/MyWebApp"
RUN dotnet build "MyWebApp.csproj" -c Release -o /app/build

I keep getting the following error message when running docker compose command:

=> ERROR [build 4/9] COPY [../../core/Logic/Logic.csproj, ../../core/Logic/] 0.0s

=> ERROR [build 5/9] COPY [../../core/Models/Models.csproj, ../../core/Models/]

We cannot restructure the folders in VS 2019 as it has been set up in that way due to some reasons. The docker file resides in MyWebApp project's folder and the docker compose file is in the parent folder of MyWebApp folder where the solution resides. Even I moved the docker file adjacent to the docker compose file but it was not conclusive.

The following code snippet is the docker-compose file:

version: '3.4'

services:
  mywebapp:
    image: ${DOCKER_REGISTRY-}mywebapp
    build:
      context: .
      dockerfile: MyWebApp/Dockerfile
    ports:
    - 8080:80
    - 8443:443

What is the workaround or solution to address this problem?

Upvotes: 0

Views: 574

Answers (1)

galdin
galdin

Reputation: 14064

If your file structure is:

docker-compose.yml
MyWebApp/MyWebApp.csproj
core/Logic/Logic.csproj
core/Models/Models.csproj

Your Dockerfile should be:

FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /src
COPY ["MyWebApp/MyWebApp.csproj", "MyWebApp/"]
COPY ["core/Logic/Logic.csproj", "../../core/Logic/"]
COPY ["core/Models/Models.csproj", "../../core/Models/"]
RUN dotnet restore "MyWebApp/MyWebApp.csproj"
COPY . .
WORKDIR "/src/MyWebApp"
RUN dotnet build "MyWebApp.csproj" -c Release -o /app/build

Why?

Because the current working directory is always the context directory. Context can be set using docker-compose's build.context field. In your example, the context is the solution root. So the Dockerfile is executed from that directory, irrespective or where it's placed.

You cannot access files outside the context directory.
Eg. if context resolves to /a/b/c, Dockerfile can't COPY or use files in /a/b/d

Upvotes: 2

Related Questions