Every so often it can be really helpful to cross compile a docker image or stage in a multi-stage build. This is especially useful where the programming language you are using supports cross-platforms builds or the tooling you are using for compilation provides good support for it.

Recently, I had this need when I was attempting to create build of a project written in node using pkg. Although I did not end up going this route in the end, I think the principal is interesting enough to talk about.

No matter the underlying platform I wanted to ensure I was getting a Linux ARM64 architecture during the docker build. You can use the same technique to build on other architectures and even more than one providing that the image you have chosen supports them.

Here I am using the official node image and it currently supports amd64, arm32v6, arm32v7, arm64v8, ppc64le and s390x.

FROM --platform=linux/amd64 node:18 as build

RUN yarn install --frozen-lockfile
RUN npx pkg ./index.js

Note the inclusion of the --platform=linux/amd64 argument to the FROM directive in the Dockerfile.

For more information the docker documentation has a helpful page that covers this functionality in more depth.