Search code examples
macosdockerqemuapple-silicon

How to determine when Docker containers (on an M1 MacBook) are running via qemu?


It has been mentioned that when employing x86_64 Docker images on an M1 Mac, when no ARM64 image is available, that container will start under qemu emulation for compatibility. (At the cost of performance.)

Often times when I'm running a collection of containers (and integration tests against the lot), I'll see qemu-system-aarch64 pegging a few cores.

My question: How can I determine, for a given list of running containers (ie. docker ps), which ones are running natively and which are being emulated?


Solution

  • This is true also for Docker running on amd64 CPU, when the image is build for arm64, and the whole mechanism is explained in this SO

    The mechanism for emulation is using the information in the elf to recognize the architecture for which the process is build, and if the architecture of the binary differs from the architecture of the CPU, it starts the qemu emulation. Though the recognizing of the architecture is more related to the process, there is still information about the targeted architecture of the docker image. The targeted architecture is determined from the "Architecture" flag on the image which was set when the image was build. Any of the containers that will run the image will be associated (trough the image) with this flag.

    It should be noted that the "Architecture" flag on the image will not prevent a single process inside the image, which is compiled for a different architecture than the flagged one to run. The reason for this is that bitfmt (which is the underlying mechanism sitting inside the linux kernel) will always try to recognize the architecture from the magic numbers of the elf and will start the the emulation if the magic number is recognized.

    To list the architecture of the containers, you can use the following "quick" query:

    for i in `docker ps --format "{{.Image}}"` ; do docker image inspect $i --format "$i -> {{.Architecture}} : {{.Os}}" ;done
    

    The command will print the container name, the architecture and the os of the image.

    To avoid typing this command multiple times, you can add alias in .bashrc as follows:

    alias docker-arch-ps='for i in `docker ps --format "{{.Image}}"` ; do docker image inspect $i --format "$i -> {{.Architecture}} : {{.Os}}" ;done';
    

    After this, you can use simple docker-arch-ps to get the list of the containers and their architecture.