Search code examples
asp.netdockerdockerfile

Dockerfile for solution with two projects


I have .NET 6 app, the folder structure is like:

TestProject
 - MyProject.sln
 - docker-compose.yaml
 - MyProject/
    - MyProject.csproj
    - Dockerfile
 - MyProject.Db/
     - MyProject.Db.csproj   

This is my Dockerfile that was auto generated by VisualStudio

# Stage 1: Base Image with ASP.NET runtime
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

# Stage 2: Build Image with SDK for compiling the application
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["/MyProject.csproj", "MyProject/"]
COPY ["/MyProject.Db/MyProject.Db.csproj", "MyProject.Db/"]

RUN dotnet restore "MyProject/MyProject.csproj"
WORKDIR "/src/MyProject"
COPY . .
RUN dotnet build "MyProject.csproj" -c Release -o /app/build

# Stage 3: Publish Image for a smaller runtime image
FROM build AS publish
RUN dotnet publish "MyProject.csproj" -c Release -o /app/publish /p:UseAppHost=false

# Stage 4: Final Image with only necessary artifacts
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyProject.dll"]

I'm getting an error saying:

 ERROR  [app build 4/8] COPY [/MyProject.Db/MyProject.Db.csproj, MyProject.Db/]:
------
failed to solve: failed to compute cache key: failed to calculate checksum of ref 9dfeae07-144f-4a1a-9a88-4816eb08f9d9::p80g09cb0geba6x3tewswlfug: "/MyProject.Db/MyProject.Db.csproj": not found

And my docker-compose file looks like that:

version: '3.8'

services:
  database:
    build:
      context: ./MyProject.Db
      dockerfile: Dockerfile
    ports:
      - "1433:1433"

  app:
    build:
      context: ./MyProject
      dockerfile: Dockerfile
    ports:
      - "8080:80"
    depends_on:
      - database

How should I fix my COPY command to make it work? I saw other solutions saying to move Dockerfile in the same folder as .sln, but I don't want to do that. Is there any other way?

Thanks.


Solution

  • I found a way to fix a problem by changing docker-compose.yaml lines to:

    app:
        build:
          context: .
          dockerfile: /MyProject/Dockerfile
    

    and Dockerfile lines to:

    COPY ["/MyProject/MyProject.csproj", "MyProject/"]
    COPY ["/MyProject.Db/MyProject.Db.csproj", "MyProject.Db/"]