How to run "dotnet publish" with the runtime flag in a multi arch Dockerfile?

1.2k Views Asked by At

I have a set of ASP.NET Core 6.0 services hosted on AWS ECS Fargate. Currently they are running on x64 but I want to experiment using the ARM architecture. Also, I want to produce multi-arch images because developers might need to pull those images locally for troubleshooting purposes.

Currently, my publish stage looks like the following

FROM build AS publish
RUN dotnet publish "API.csproj" -c Release -o /app/publish -r linux-x64 --sc

Note the -r linux-x64.

So here is the question:

Assuming I'm using buildx build to build the image,

docker buildx build -f .\src\apps\API\Dockerfile -t api --platform linux/amd64,linux/arm64 .

How can I pass the proper architecture to the dotnet publish command?

1

There are 1 best solutions below

0
On

Buildx provides the argument TARGETARCH, you can try that. So this argument gets the corresponding architecture when it's passed via the buildx command line. For example: Dockerfile

FROM build AS publish
ARG TARGETARCH 
RUN dotnet publish "API.csproj" -c Release -o /app/publish -r $TARGETARCH --sc

So if you're building the image like docker buildx build -f .\src\apps\API\Dockerfile -t api --platform linux/amd64,linux/arm64 . The TARGETARCH will get values amd64 and arm64

If you need to get your desired string you can extract the publish command into a separate bash script and use any conditional statement to get your desired values. So something like, publish.sh :

#!/bin/bash

TARGETARCH=$1

if [ "$TARGETARCH" == "amd64" ]; then
    dotnet publish "API.csproj" -c Release -o /app/publish -r linux-x64 --sc
elif [ "$TARGETARCH" == "arm64" ]; then
    dotnet publish "API.csproj" -c Release -o /app/publish -r linux-arm64 --sc
fi

and the final Dockerfile would be like

FROM build AS publish
ARG TARGETARCH
COPY ./publish.sh /
RUN /publish.sh $TARGETARCH