Search code examples
dockerdockerfiledocker-image

How to change the image name from the Dockerfile based on the platform?


I am trying to use Dockerfile to build docker image.

How can I create a conditional check based on the platform in Dockerfile.

For example,

FROM --platform=$BUILDPLATFORM golang:alpine AS build
ARG BUILDPLATFORM

IF ${BUILDPLATFORM} == 'windows'
FROM mcr.microsoft.com/dotnet/aspnet:8.0
ELSE 
FROM mcr.microsoft.com/dotnet/aspnet:8.0-windowsservercore-ltsc2022

Solution

  • You're better off fixing the base image so this isn't necessary, possibly building your own base image. But to do it this way, here's an option that requires you define all of the platforms:

    ARG BUILDOS
    ARG BUILDPLATFORM
    FROM --platform=$BUILDPLATFORM golang:alpine AS build
    # ...
    
    FROM mcr.microsoft.com/dotnet/aspnet:8.0 as dotnet-base-windows
    FROM mcr.microsoft.com/dotnet/aspnet:8.0-windowsservercore-ltsc2022 as dotnet-base-linux
    FROM dotnet-base-${BUILDOS}
    # ...