To have all packages ready you need restore before building. To have all packages during the build you need to copy the packages.
Here is an example in form of an experiment:
Preparation:
Have the sdk ready: docker pull microsoft/dotnet:2.2-sdk.
Have src/src.csproj ready:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="12.0.2" /> </ItemGroup> </Project>
Have src/Dockerfile ready:
FROM microsoft/dotnet:2.2-sdk AS byse COPY packages /root/.nuget/packages COPY src src RUN ls /root/.nuget/packages WORKDIR /src RUN dotnet restore RUN ls /root/.nuget/packages
Execution:
Restore the Packages:
docker run --rm -v $(pwd)/src:/src -v $(pwd)/packages:/root/.nuget/packages -w /src microsoft/dotnet:2.2-sdk dotnet restore
Build the Image:
docker build -t test -f src/Dockerfile .
Expectation:
Sending build context to Docker daemon 13.77MB Step 1/7 : FROM microsoft/dotnet:2.2-sdk AS byse ---> e4747ec2aaff Step 2/7 : COPY packages /root/.nuget/packages ---> 76c3e9869bb4 Step 3/7 : COPY src src ---> f0d3f8d9af0a Step 4/7 : RUN ls /root/.nuget/packages ---> Running in 8323a9ba8cc6 newtonsoft.json Removing intermediate container 8323a9ba8cc6 ---> d90056004474 Step 5/7 : WORKDIR /src ---> Running in f879d52f81a7 Removing intermediate container f879d52f81a7 ---> 4020c789c338 Step 6/7 : RUN dotnet restore ---> Running in ab62a031ce8a Restore completed in 44.28 ms for /src/src.csproj. Removing intermediate container ab62a031ce8a ---> 2cd0c01fc25d Step 7/7 : RUN ls /root/.nuget/packages ---> Running in 1ab3310e2f4c newtonsoft.json Removing intermediate container 1ab3310e2f4c ---> 977e59f0eb10 Successfully built 977e59f0eb10 Successfully tagged test:latest
Note that the ls steps are cached and would not print on a subsequent call. Run docker rmi test to reset.
Step 4/7 runs before the restore and the packages are already cached.
Step 4/7 : RUN ls /root/.nuget/packages ---> Running in 8323a9ba8cc6 newtonsoft.json
This can solves excessive restore times for example during automated builds.
To solve your network issue you can try to mount the network patch instead of the local path during the resolve step or robocopy files from your corp network into a local cache first.