Building ASP.NET Core docker image on Azure DevOps : no such file or directory

Pragmatism - DevOps - CloudNative - .NET

Building ASP.NET Core docker image on Azure DevOps : no such file or directory

index-hero

Note : This post was initialy posted at https://pragma3.wordpress.com/2019/05/23/building-asp-net-core-docker-image-on-azure-devops-no-such-file-or-directory/

When you try to build a docker image for a default ASP.NET Core project template on Azure DevOps for the first time, you should encounter the following error :

Step 6/26 : COPY [« TestClassicApp.Api1/TestClassicApp.Api1.csproj », « TestClassicApp.Api1/ »]

COPY failed: stat /var/lib/docker/tmp/docker-builder260812138/TestClassicApp.Api1/TestClassicApp.Api1.csproj: no such file or directory

##[error]COPY failed: stat /var/lib/docker/tmp/docker-builder260812138/TestClassicApp.Api1/TestClassicApp.Api1.csproj: no such file or directory

##[error]/usr/bin/docker failed with return code: 1

From Azure DevOps logs.

It will be the case if you have a hierarchy in your solution folder where your projects are placed in subfolders.

Problem

The problem comes from the fact that, by default, the docker build task run with the buildContext set to ** (equivalent to the Dockerfile directory). If your project is placed in a subfolder like the sample above, it won’t work.

If we look closer at the Dockerfile instruction, we’ll see that the COPY operation use the full path to the csproj : COPY [« TestClassicApp.Api1/TestClassicApp.Api1.csproj », « TestClassicApp.Api1/ »]. Since we are in the context of the Dockerfile location, there’s no subfolder TestClassicApp.Api1 as the Dockerfile is currently in this folder.

Solution

The simple fix is to specify a parameter to the Docker build task named buildContext :

task: Docker@2
displayName: Build and push an image to container registry
inputs:
  command: buildAndPush
  repository: $(imageRepository)
  dockerfile: $(dockerfilePath)
  containerRegistry: $(dockerRegistryServiceConnection)
  buildContext: .
  tags: |
    $(tag)

Hope this will help other people !