DEV Community

K@zuki.
K@zuki.

Posted on

Switching FROM Docker Images for Each CPU Architecture

Introduction

This article explains how to switch Docker's FROM according to the CPU architecture when multiple CPU architectures exist.
For example, it is useful when supporting Apple Silicon.

Exclusions for this article

Please note that this article does not cover cases where images for each platform are provided with the same tag or where architecture identification is included in the tag.

For example, the following cases:

# Multiple platforms are provided with the same tag
FROM alpine:3
Enter fullscreen mode Exit fullscreen mode
# Different tags, but architecture identification is included in the tag
# - example:amd64
# - example:arm64
FROM example:${TARGETARCH}
Enter fullscreen mode Exit fullscreen mode

These are, of course, common patterns.
The method introduced this time may also be a common pattern, but it was difficult to find, so I would like to share it.

Motivation

When building multiple platform images with docker/build-push-action in one step of GitHub Actions, it is necessary to prepare separate images for each CPU architecture.
If you prepare an image for each architecture, docker manifest and other tools require some effort to distribute multiple platform images with the same tag. ※1
Therefore, if you can combine it into one step, you can maintain a very simple workflow.

While writing this article, I am thinking that a method that can be easily done without doing such a strange thing may have already been born.

How to switch FROM according to CPU architecture

This article explains how to switch Docker's FROM according to the CPU architecture, using ubuntu:22.04 for amd64 and alpine:3 for arm64 as an example.

Before creating the final product, you can switch images to different ones for each CPU architecture by preparing stages such as amd64 and arm64.

FROM ubuntu:22.04 as amd64
RUN ...

FROM alpine:3 as arm64
RUN ...

FROM ${TARGETARCH} as app
Enter fullscreen mode Exit fullscreen mode

Although only variables provided in advance such as ARG and TARGETARCH can be specified for FROM itself, you can switch FROM by preparing stages such as amd64 and arm64.

It's obvious, but I was struggling for about an hour, so if you want to do something else, please refer to it.

Conclusion

This article explains how to switch Docker's FROM according to the CPU architecture.
By using this method, you can develop more efficiently when multiple CPU architectures exist.

Top comments (0)