简体   繁体   中英

.NET 7 Multi-platform docker build - how to conditionally change target platform in Dockerfile?

I have a Dockerfile for a .NET7 app which I am building with docker buildx for both linux/amd64 and linux/arm64. This works all fine.

How I would like to optimize my build based on this sample to include the proper target platform on the do.net restore/publish command. But I couldn't figure out so far how to do this conditionally inside the Dockerfile.

I have this so far, but of course this doesn't work since the variables from the first RUN command are not persisted to the following commands.

Any ideas are appreciated!

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build-env

ARG TARGETPLATFORM
ARG BUILDPLATFORM

RUN echo "I am running on $BUILDPLATFORM, building for $TARGETPLATFORM" > /log

# The following works but does not persist on to the next RUN

RUN if [ "$TARGETPLATFORM" = "linux/arm64 " ] ; then DOTNET_TARGET=linux-musl-arm64 ; else DOTNET_TARGET=linux-x64 ; fi

WORKDIR /app
COPY . ./
RUN dotnet restore MyApp -r $DOTNET_TARGET /p:PublishReadyToRun=true
RUN dotnet publish MyApp  -c Release -o Ahs.AuthManager/out -r $DOTNET_TARGET --self-contained true --no-restore /p:PublishTrimmed=true /p:PublishReadyToRun=true /p:PublishSingleFile=true

## more to follow here...

The DO.NET_TARGET variable you set doesn't keep its state once that instruction has executed because each RUN instruction uses a new shell. You can either persist the value to a file to be read from later or inline the setting of the variable with the commands that use it.

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build-env

ARG TARGETPLATFORM
ARG BUILDPLATFORM

RUN echo "I am running on $BUILDPLATFORM, building for $TARGETPLATFORM" > /log

# The following works but does not persist on to the next RUN

RUN if [ "$TARGETPLATFORM" = "linux/arm64 " ] ; then DOTNET_TARGET=linux-musl-arm64 ; else DOTNET_TARGET=linux-x64 ; fi \
    && echo $DOTNET_TARGET > /tmp/rid

WORKDIR /app
COPY . ./
RUN dotnet restore MyApp -r $(cat /tmp/rid) /p:PublishReadyToRun=true
RUN dotnet publish MyApp  -c Release -o Ahs.AuthManager/out -r $(cat /tmp/rid) --self-contained true --no-restore /p:PublishTrimmed=true /p:PublishReadyToRun=true /p:PublishSingleFile=true

## more to follow here...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM