Forcing docker to use linux/amd64 platform by default on macOS

Current beta version of docker requires you to specify a --platform=linux/amd64 each time you need to build or run an amd64 image/container.

The documentation mentions

When running an image with multi-architecture support, docker will automatically select an image variant which matches your OS and architecture.

The documentation does not specify a way to alter this automatic behaviour using env variables. It seems to ignore both BUILDPLATFORM and TARGETPLATFORM.

Is there any other way to force docker to run all build and run commands with a platform linux/amd64 instead of linux/arm64/v8 by default on macOS running on apple-silicon?

91817 次浏览

You can set the environment variable DOCKER_DEFAULT_PLATFORM

export DOCKER_DEFAULT_PLATFORM=linux/amd64

Docker images built with Apple Silicon (or another ARM64 based architecture) can create issues when deploying the images to a Linux or Windows based AMD64 environment (e.g. AWS EC2, ECS, etc.) For example, you may try to upload your docker image made on the M1 chip to an AWS ECR repository and it fails to run. Therefore, you need a way to build AMD64 based images on the ARM64 architecture, whether it's using Docker build (for individual images) or docker-compose build (e.g. for multi-image apps running in a docker compose network).

For building single docker images: Set your environment variable using the command line or modifying your .bashrc or .zshenv file as suggested in the accepted answer.

export DOCKER_DEFAULT_PLATFORM=linux/amd64

Alternatively, in the Dockerfile, include the following flag in the FROM command (for a multi-stage Dockerfile build, the flag is only needed for the first stage):

FROM --platform=linux/amd64 python:3.7-alpine

For building images as part of a docker-compose build, include the platform: linux/amd64 for each service. For example:

services:
frontend:
platform: linux/amd64
build: frontend
ports:
- 80:80
depends_on:
- backend
backend:
platform: linux/amd64
build: backend

You don't need to export the env variable as mentioned in one of the answers, you can run it as part of the command a single time by doing:

DOCKER_DEFAULT_PLATFORM=linux/amd64 docker-compose build

Keep in mind that if you've already downloaded the image for a different platform, docker will keep using that image no matter what platform you specify as your default, you would delete the image using docker image rm your_img first to fix that.

You can use buildx (mobi) which suipport cli for platform.

docker buildx build --platform linux/amd64 .

You can add in your docker-compose.yaml

services:
service_name:
environment:
- DOCKER_DEFAULT_PLATFORM=linux/amd64

you can set

export DOCKER_DEFAULT_PLATFORM=linux/amd64

in a .zshrc file for Mac M1