dockerdockerfilebuildx

Set condition based on CPU-Arch in Dockerfile


I need to download and install a package directly from GitHub and I need to install some libraries I need for a build from source through pip down the line.

For that I use:

RUN apt-get update && apt-get install -y libavformat-dev libavdevice-dev libavfilter-dev libswscale-dev

and

RUN wget https://github.com/mozilla/geckodriver/releases/download/v0.30.0/geckodriver-v0.30.0-linux64.tar.gz \
&& tar -xf geckodriver-v0.30.0-linux64.tar.gz \
&& mv geckodriver /usr/local/bin/ \
&& rm geckodriver-v0.30.0-linux64.tar.gz

I want to build for different platforms with buildx: docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 .

On amd64 I do not need to install the av libraries, as pip won't need to build anything, because wheels are provided. On arm64 and arm/v7 I need to install the libraries, and I need to download, extract and copy a different geckodriver package.

Is there a way to specify conditional statements based on CPU architecture?


Solution

  • As Daniel mentioned, Docker provides predefined environmental variables that are accessible at container build time.

    We don't need to do anything Docker specific with these however, we can simply use them in a bash script condition:

    FROM python:3-bullseye
    
    RUN apt-get update && apt-get install -y ffmpeg firefox-esr npm
    ARG TARGETARCH
    RUN if [ $TARGETARCH = "arm64" ]; then \
            apt-get install -y libavformat-dev libavdevice-dev python3-av \
        ; fi
    RUN npm install -g webdriver-manager
    RUN webdriver-manager update --gecko
    

    Note the necessary specification of ARG TARGETARCH to make that environmental variable accessible by dispatched processes at build time.