dotnet-docker icon indicating copy to clipboard operation
dotnet-docker copied to clipboard

Enable using docker build `--platform` switch (easily)

Open richlander opened this issue 3 years ago • 44 comments

There is no way to write a Dockerfile for .NET that is (A) succinct, (B) easy to build from the command line, (C) can equally produce Arm64 or x64 images, (D) that will run equally well on both Arm64 and x64 machines, and (E) avoids running the SDK in an emulator (since .NET doesn't support running in QEMU).

The following Dockerfile (which doesn't currently work) would satisfy all four of these requirements.

ARG BUILDARCH
FROM mcr.microsoft.com/dotnet/sdk:7.0-bullseye-slim-$BUILDARCH AS build
ARG TARGETARCH
WORKDIR /source

# copy csproj and restore as distinct layers
COPY aspnetapp/*.csproj .
RUN dotnet restore -r linux-$TARGETARCH

# copy everything else and build app
COPY aspnetapp/. .
RUN dotnet publish -c Release -r linux-$TARGETARCH --self-contained false --no-restore -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/aspnet:7.0-bullseye-slim
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["./aspnetapp"]

Note: The two ENVs are set via Docker, not my invention. Context: https://github.com/dotnet/dotnet-docker/pull/4387#issuecomment-1416565213. The reason this Dockerfile doesn't work is because -r expects x64 not amd64 (which $TARGETARCH returns) and our container tags expect arm64v8 not arm64 (which $BUILDARCH returns). Funny enough, $TARGETARCH returns arm64 for Arm64, which -r likes fine and $BUILDARCH returns amd64 for x64, which our container tags like fine.

Note: Close readers may wonder why $TARGETARCH is not needed for the last FROM statement. That's because --platform is picking the correct image from the multi-arch tag. We could use $TARGETARCH if we wanted, but it is unnecessary since the underlying mechanics will do the right thing. How would one know that the tag is a multi-arch tag just by looking at it? It's because it doesn't include an architecture.

It would enable the following scenarios:

  • docker build -- will produce a native-arch result on both Arm64 and x64 and use the native arch SDK.
  • docker build --platform linux/arm64 -- Will produce an Arm64 container image on both Arm64 and x64 machines but run the SDK as native-arch, avoiding emulation (on x64 machines).
  • docker build --platform linux/amd64 -- Same as above, but will produce an x64 container images, and similarly avoid emulation (on Arm64 machines).
  • docker buildx build --platform linux/amd64,linux/arm64 -- Same as above, but will produce both Arm64 and x64 container images, and similarly avoid emulation.

Note that the resulting image will not run in emulation. That's the not the purpose of this proposal. Instead, the purpose is to reliably avoid emulation and to make it easy, for example, to build x64 container images on an Apple M1 box and push those to an x64 cloud. You'd be able to do that via the --platform switch and not need to do anything else (other than follow the pattern used in the Dockerfile).

It requires two things:

  • For Arm64, we need to push container tags as arm64 (matching $BUILDARCH) in addition to arm64v8.
  • For x64, teaching the CLI to replace linux-amd64 (matching $TARGETARCH) with linux-x64

The proposal is to make these changes for .NET 6+.

The alternative is the following.

ARG SDKARCH=amd64
FROM mcr.microsoft.com/dotnet/sdk:7.0-bullseye-slim-$SDKARCH AS build

ARG TARGETARCH
RUN arch=$TARGETARCH \
    && if [ "$TARGETARCH" = "amd64" ]; then arch="x64"; fi \
    && echo $arch > /tmp/arch

WORKDIR /source

# copy csproj and restore as distinct layers
COPY aspnetapp/*.csproj .
RUN dotnet restore -r linux-$(cat /tmp/arch)

# copy everything else and build app
COPY aspnetapp/. .
RUN dotnet publish -r linux-$(cat /tmp/arch) -c Release --self-contained false --no-restore -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/aspnet:7.0-bullseye-slim
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["./aspnetapp"]

Inspiration: https://github.com/dotnet/dotnet-docker/pull/4387#issuecomment-1416454071

SDKARCH needs to have a default, so you need to know to set the ARG on whatever platform isn't the default. Here, I'm choosing x64 (or really "amd64") as the default. Also, you cannot run any code before the first FROM since a Dockerfile isn't bash.

This pattern enables the following scenarios:

  • docker build -- only works correctly on x64 and breaks on Arm64 (dotnet restore just hangs),
  • docker build --build-arg SDKARCH=arm64v8 -- builds an Arm64 image on an Arm64 machine, not because the ARG is set, however. The ARG just enables the SDK to run with the native arch.
  • docker build --platform linux/arm64 -- Doesn't do anything useful, same for specifying linux/amd64.
  • docker build buildx --platform linux/amd64,linux/arm64 -- Doesn't work.
  • docker build buildx --platform linux/amd64,linux/arm64 --build-arg SDKARCH=arm64v8 -- Produces both Arm64 and x64 container images.

richlander avatar Feb 06 '23 01:02 richlander

Relates to:

  • https://github.com/NuGet/Home/issues/12227
  • https://github.com/dotnet/dotnet-docker/issues/3338
  • https://github.com/dotnet/aspnetcore/issues/46306
  • https://github.com/dotnet/core/pull/8163

@nagilson @baronfel @marcpopMSFT @elinor-fung

richlander avatar Feb 06 '23 01:02 richlander

[Triage] Short-term we need to update our customer guidance for this scenario since the current guidance is incompatible with the functionality of .NET 7. The alternative Dockerfile that was provided above with the SDKARCH is probably the best approach identified at this point for a workable solution that's possible today.

Long-term we need to come up with a design that can work. Ideally it would be great if we could eliminate the need for a set of variant-less tags (e.g. arm64). There does exist a $TARGETVARIANT variable that may help with this. But it seems to only be set for Arm32 scenarios. Then we'd need to get buyoff from the CLI for implementing some kind of RID aliasing between x64 and amd64.

This also affects the scaffolded Dockerfiles produced by the VS Container Tools. They are generating the old "multi-arch" Dockerfile that no longer works with .NET 7 when targeting an architecture that differs from the host.

mthalman avatar Feb 06 '23 19:02 mthalman

@richlander, In your proposed Dockerfile

ARG BUILDARCH
FROM mcr.microsoft.com/dotnet/sdk:7.0-bullseye-slim-$BUILDARCH AS build
ARG TARGETARCH
WORKDIR /source

# copy csproj and restore as distinct layers
COPY aspnetapp/*.csproj .
RUN dotnet restore -r linux-$TARGETARCH

# copy everything else and build app
COPY aspnetapp/. .
RUN dotnet publish -c Release -r linux-$TARGETARCH --self-contained false --no-restore -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/aspnet:7.0-bullseye-slim
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["./aspnetapp"]

Have you considered utilizing the --platform option within the FROM statement? This feels like it could simplify the Dockerfile, work with the existing Dockerfile constructs, and not require any tagging derivations from the norm.

FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:7.0-bullseye-slim AS build
ARG TARGETARCH
WORKDIR /source

# copy csproj and restore as distinct layers
COPY aspnetapp/*.csproj .
RUN dotnet restore -r linux-$TARGETARCH

# copy everything else and build app
COPY aspnetapp/. .
RUN dotnet publish -c Release -r linux-$TARGETARCH --self-contained false --no-restore -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/aspnet:7.0-bullseye-slim
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["./aspnetapp"]

MichaelSimons avatar Feb 07 '23 20:02 MichaelSimons

That looks awesome! Ship it! I didn't know about that pattern.

That means we just need to fix the RID problem.

richlander avatar Feb 07 '23 22:02 richlander

Just wonder about this and Native AOT. Will this pattern not work for that? I think it doesn't have a cross-arch cross-build story. Is that right @jkotas?

richlander avatar Feb 17 '23 17:02 richlander

NativeAOT has cross-arch cross-build story. It is documented here: https://github.com/dotnet/runtime/blob/main/src/coreclr/nativeaot/docs/compiling.md#cross-architecture-compilation . For Linux, it requires rootfs matching the target platform.

jkotas avatar Feb 17 '23 18:02 jkotas

If it helps, https://github.com/dotnet/samples/tree/main/core/nativeaot/HelloWorld is nativeaot sample that includes Linux x64 and Windows x64 docker files for building it (the sample does not have cross-arch build support).

jkotas avatar Feb 17 '23 18:02 jkotas

Issue for NativeAOT scenario investigation is at https://github.com/dotnet/dotnet-docker/issues/4129

mthalman avatar Feb 21 '23 15:02 mthalman

That means we just need to fix the RID problem.

The RID fix is in, thanks to a new hire on our team @JL03-Yue who worked on it. 😄 Is there anything else required here @richlander ?

nagilson avatar Mar 06 '23 18:03 nagilson

It works great! I tested it with dotnetapp and the following Dockerfile.

To recap, we want to be able to build Arm64 and x64 assets on an Apple Arm64 machine safetly and correctly. We now can (with .NET 8 Preview 3). We are going to look at backporting the change to .NET 7 as well.

The Dockerfile references a multi-platform tag that references Amd64, Arm64, and Arm32 images that include a .NET 8 Preview 3 SDK.

Note: This test repo will be deleted before long, so don't be surprised if you read this later and the sample doesn't work. You'll need to switch to the real .NET 8 SDK image. It's called "dotnetnonroot" since I was using for testing another feature.

# To learn about building .NET container images:
# https://github.com/dotnet/dotnet-docker/blob/main/samples/README.md
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/nightly/sdk:8.0-preview AS build
ARG TARGETARCH
WORKDIR /source

# copy csproj and restore as distinct layers
COPY *.csproj .
RUN dotnet restore -a $TARGETARCH

# copy and publish app and libraries
COPY . .
RUN dotnet publish -a $TARGETARCH --self-contained false --no-restore -o /app

# To enable globalization:
# https://github.com/dotnet/dotnet-docker/blob/main/samples/enable-globalization.md
# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:7.0-jammy
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["./dotnetapp"]

Some quick tests on my Apple M1 machine.

% docker build -t dotnetapp .
% docker inspect dotnetapp -f "{{.Os}}\{{.Architecture}}"
linux\arm64
% docker run --rm dotnetapp | grep Arch        
OSArchitecture: Arm64
% docker build -t dotnetapp --platform linux/arm64 .
% docker inspect dotnetapp -f "{{.Os}}\{{.Architecture}}"
linux\arm64
% docker run --rm dotnetapp | grep Arch
OSArchitecture: Arm64
% docker build -t dotnetapp --platform linux/amd64  .
% docker inspect dotnetapp -f "{{.Os}}\{{.Architecture}}"
linux\amd64
% docker build -t dotnetapp --platform linux/arm .
% docker inspect dotnetapp -f "{{.Os}}\{{.Architecture}}"
linux\arm

I didn't run the generated Amd64 and Arm32 images on my Arm64 machine since they don't work in that environment. The key point is that you can build images for all the architectures with one Dockerfile using the --platform switch to control the outcome. The native arch is always the default.

I tested the same scenarios and they worked on my x64 machine as well.

We can have even more fun with docker buildx.

% docker buildx build -f Dockerfile.ubuntu --platform linux/amd64,linux/arm64,linux/arm -t dotnetnonroot.azurecr.io/dotnetapp --push .

On my Apple M1 machine:

% docker run --rm -it dotnetnonroot.azurecr.io/dotnetapp
         42                                                    
         42              ,d                             ,d     
         42              42                             42     
 ,adPPYb,42  ,adPPYba, MM42MMM 8b,dPPYba,   ,adPPYba, MM42MMM  
a8"    `Y42 a8"     "8a  42    42P'   `"8a a8P_____42   42     
8b       42 8b       d8  42    42       42 8PP!!!!!!!   42     
"8a,   ,d42 "8a,   ,a8"  42,   42       42 "8b,   ,aa   42,    
 `"8bbdP"Y8  `"YbbdP"'   "Y428 42       42  `"Ybbd8"'   "Y428  

.NET 7.0.3
Ubuntu 22.04.2 LTS

UserName: root
OSArchitecture: Arm64
ProcessorCount: 4
TotalAvailableMemoryBytes: 4124512256 (3.00 GiB)

On my x64 machine:

# docker run --rm -it dotnetnonroot.azurecr.io/dotnetapp
         42
         42              ,d                             ,d
         42              42                             42
 ,adPPYb,42  ,adPPYba, MM42MMM 8b,dPPYba,   ,adPPYba, MM42MMM
a8"    `Y42 a8"     "8a  42    42P'   `"8a a8P_____42   42
8b       42 8b       d8  42    42       42 8PP!!!!!!!   42
"8a,   ,d42 "8a,   ,a8"  42,   42       42 "8b,   ,aa   42,
 `"8bbdP"Y8  `"YbbdP"'   "Y428 42       42  `"Ybbd8"'   "Y428

.NET 7.0.3
Ubuntu 22.04.2 LTS

UserName: root
OSArchitecture: X64
ProcessorCount: 12
TotalAvailableMemoryBytes: 33444470784 (31.00 GiB)
cgroup memory constraint: /sys/fs/cgroup/memory/memory.limit_in_bytes
cgroup memory limit: 9223372036854771712 (8589934591.00 GiB)
cgroup memory usage: 6713344 (6.00 MiB)
GC Hard limit %: 0

On my Arm64 Raspberry Pi:

 $ docker run --rm -it dotnetnonroot.azurecr.io/dotnetapp
         42
         42              ,d                             ,d
         42              42                             42
 ,adPPYb,42  ,adPPYba, MM42MMM 8b,dPPYba,   ,adPPYba, MM42MMM
a8"    `Y42 a8"     "8a  42    42P'   `"8a a8P_____42   42
8b       42 8b       d8  42    42       42 8PP!!!!!!!   42
"8a,   ,d42 "8a,   ,a8"  42,   42       42 "8b,   ,aa   42,
 `"8bbdP"Y8  `"YbbdP"'   "Y428 42       42  `"Ybbd8"'   "Y428

.NET 7.0.3
Ubuntu 22.04.2 LTS

UserName: root
OSArchitecture: Arm64
ProcessorCount: 4
TotalAvailableMemoryBytes: 3978678272 (3.00 GiB)

richlander avatar Mar 07 '23 23:03 richlander

This experience will ship in:

  • 8.0 P3
  • 7.0.300

richlander avatar Mar 15 '23 23:03 richlander

If you want this experience now, you can use: mcr.microsoft.com/dotnet/nightly/sdk:8.0-preview

richlander avatar Mar 15 '23 23:03 richlander

If you want this experience now, you can use: mcr.microsoft.com/dotnet/nightly/sdk:8.0-preview

Excellent news @richlander! Thanks for this. I've tried this on my M1 and on a x64 machine and was able to successfully build amd64 and arm64 with buildx on both.

docker buildx build --platform linux/amd64,linux/arm64 -t image:tag . --no-cache

goncalo-oliveira avatar Mar 16 '23 10:03 goncalo-oliveira

@richlander I seem to be having some issues with the RUN dotnet lines in the Dockerfile you provided

The command I am using is similar to @goncalo-oliveira's docker buildx one but I suspect their Dockerfile might have omitted the -a $TARGETARCH switches.

  1. dotnet restore doesn't appear to have an -a flag
  2. dotnet publish appears to be expecting linux-x64 but instead it is getting linux-amd64 - Linux RIDs

Thanks for looking into this

campbellwray avatar Mar 16 '23 20:03 campbellwray

Both your observations are 100% true. You've also identified what we fixed in 8.0 P3 and (in future) 7.0.300.

I updated the Dockerfile example to use a 8.0 P3 nightly build instead of the hacked build I was using before. That should work better. I just tested it. Please tell me if it doesn't.

richlander avatar Mar 17 '23 00:03 richlander

Ahh apologies, I was unintentionally using mcr.microsoft.com/dotnet/nightly/aspnet:8.0-preview-bullseye-slim, I didn't realise that there was no bullseye version of P3 available, I must have been downloading a much older build.

Unfortunately even with this resolved I was still unable to compile my project, it is aspnet and not runtime, and it is complaining that version 8.0 P3 is not available for the Microsoft.NETCore.App.Host.linux-arm64 package on NuGet.

error NU1102: Unable to find package Microsoft.NETCore.App.Host.linux-arm64 with version (= 8.0.0-preview.3.23165.10)
error NU1102:   - Found 117 version(s) in nuget.org [ Nearest version: 8.0.0-preview.2.23128.3 ]

I supposed that means that I will need to wait for either 8.0 P3 or 7.0.300 to be publicly released

Thanks again for all of your work on this @richlander, it is much appreciated

campbellwray avatar Mar 17 '23 03:03 campbellwray

We moved to Bookworm -> https://devblogs.microsoft.com/dotnet/announcing-dotnet-8-preview-1/#net-container-images

Ya. You get those errors with nightly builds. Try adding this nuget.config: https://github.com/dotnet/installer#installers-and-binaries

richlander avatar Mar 17 '23 03:03 richlander

Unfortunately even with this resolved I was still unable to compile my project, it is aspnet and not runtime, and it is complaining that version 8.0 P3 is not available for the Microsoft.NETCore.App.Host.linux-arm64 package on NuGet.

@campbellwray are you by any chance using 8.0 P3 on the runtime also? You only need 8.0 P3 on the builder side of things. On the runtime, you should probably continue using 7.0 - that is, assuming your project's target framework is still .NET 7.

This is the Dockerfile I'm using, without issues on both arm64 and amd64 machines, building with --platform linux/amd64,linux/arm64 on both.

# Builder
# 
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/nightly/sdk:8.0-preview AS build
ARG TARGETARCH

# ...
RUN dotnet restore -a $TARGETARCH

# ...
RUN dotnet publish -c release -a $TARGETARCH -o dist project.csproj

# Runtime
# 
FROM mcr.microsoft.com/dotnet/aspnet:7.0 as final

# ...

goncalo-oliveira avatar Mar 17 '23 09:03 goncalo-oliveira

@goncalo-oliveira thank you! I am quite new with Docker for .NET and didn't realise I could build with .NET 8 but continue to run with .NET 7, this is very helpful and has resolved my issues

Thanks again to you both 🥇

campbellwray avatar Mar 17 '23 13:03 campbellwray

This is correct. Newer SDKs support building projects that target older .NET versions. The SDK downloads the targeting pack and any other assets required.

Separately, the way that ENVs work in Dockerfiles can be a bit confusing. You need to ensure you have a ARG TARGETARCH line within the build stage where you use it. If you put that line right after the FROM, it works. Some Dockerfiles have different structures. For example, if we were to upgrade the following Dockerfile, the ENV would appear at line 9, not line 4.

https://github.com/dotnet/AspNetCore.Docs.Samples/blob/2f3a9a6af0e4fb5289d880b6003771ed458c5bdd/tutorials/scalable-razor-apps/start/Dockerfile#L8-L9

richlander avatar Mar 17 '23 15:03 richlander