Azure DevOps Pipeline: COPY failed: stat /var/lib/docker/…: no such file or directory

Summary

Running a docker build task in an Azure DevOps pipeline causes no such file or directory error.

...
Step 7/26 : COPY ["Hello-Blazor/Hello-Blazor.csproj", "Hello-Blazor/"]
COPY failed: stat /var/lib/docker/tmp/docker-builder890404231/Hello-Blazor/Hello-Blazor.csproj: no such file or directory
##[error]COPY failed: stat /var/lib/docker/tmp/docker-builder890404231/Hello-Blazor/Hello-Blazor.csproj: no such file or directory
##[error]The process '/usr/bin/docker' failed with exit code 1
Finishing: Build an image

The error occurs when the pipeline task build context does not match the build context defined in the Dockerfile. By default it assumes the Dockerfile directory which is not always the case for Visual Studio generated solutions/projects. A buildContext attribute can be added to the pipeline task to explicitly set the build context directory required by the Dockerfile.

... 
buildContext: '$(Build.SourcesDirectory)/Hello-Blazor/'
...

Description

For the detailed cause of this error refer to http://torbenp.com/2020/07/copy-failed-no-such-file-or-directory/
The Azure Pipeline task needs to be explicitly configured to execute the docker build from the parent folder defined by the Dockerfile as it will otherwise assume the Dockerfile folder as the build context. The following shows the default pipeline task without an explicit build context.

...
    - task: Docker@2
      displayName: Build an image
      inputs:
        command: build
        dockerfile: '$(Build.SourcesDirectory)/Hello-Blazor/Hello-Blazor/Dockerfile'
        tags: |
          $(tag)
...

This can create a COPY build failure with the following details:

COPY error from Azure DevOps Pipeline
Azure DevOps Pipeline COPY Error

To make the parent folder of the Dockerfile the build context, add the ‘buildContext’ attribute to the pipeline task configuration.

...
    - task: Docker@2
      displayName: Build an image
      inputs:
        command: build
        dockerfile: '$(Build.SourcesDirectory)/Hello-Blazor/Hello-Blazor/Dockerfile'
        buildContext: '$(Build.SourcesDirectory)/Hello-Blazor/'
        tags: |
          $(tag)
...

3 thoughts on “Azure DevOps Pipeline: COPY failed: stat /var/lib/docker/…: no such file or directory

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.