Reputation: 16178
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 dotnet 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...
Upvotes: 0
Views: 1297
Reputation: 3985
The DOTNET_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...
Upvotes: 2