Building Docker Images for Different Architectures.
2 min read
When we ask Docker to build an image on our laptops, Docker builds one that works with our PC. This involves building an image for that specific operating system and system architecture. In the real world, different machines run different OS on different architectures. Having to build an image for a system running a different OS/architecture isn't strange. This short article shows some ways of doing this.
Using DOCKER_DEFAULT_PLATFORM environment variable
Docker allows a user to set the default platform for builds to be. If it isn’t set, it defaults to the environment of the builder's machine. This environment variable can be set in the terminal used for building the image. This is done by running
export DOCKER_DEFAULT_PLATFORM=linux/amd64 or modifying your .bashrc or .zshenv to contain the command. This would default your build platform to
linux/amd64 for any build initiated in the current shell.
Setting the platform in the Dockerfile
In the Dockerfile, we can set the platform in the FROM command. This is done as follows.
FROM --platform=linux/arm64 python:3.7-alpine.. This would pull
linux/arm64 and build the image based on that.
If you find yourself building images for different platforms on a regular basis, this is a great way to go. Changing the environment variable every time you wish to build for another platform can be stressful. This is my favourite method of setting what platform I would love to build for.
This is the simplest way of building images for another platform. There are better ways to do this using a Docker CLI plugin called BuildX. Below are few resources to get you started. Cheers!