How to build your Docker image using the same Dockerfile regardless of the host architecture

Problem

If you are now using docker on a Mac M1 (arm64 platform), you don’t want to use amd64 as the architecture for your Linux Images.

You could have 2 lines on your Dockerfile and comment each one depending on where you’re building the image

Dockerfile

# Building on Apple Silicon host
FROM --platform=linux/arm64 ubuntu:20.04

# Building on Intel/x86_64 host
#FROM --platform=linux/amd64 ubuntu:20.04

Eventually this becomes very annoying.

Solution

You can pass a build time argument when you invoke docker build

Put this on your Dockerfile:

ARG BUILDPLATFORM
FROM --platform=linux/$BUILDPLATFORM ubuntu:20.04

On your docker_build_image.sh script:

export BUILDPLATFORM=`uname -m`
docker build --build-arg BUILDPLATFORM=${BUILDPLATFORM} -t myimagename .

Leave a Reply

Your email address will not be published. Required fields are marked *