Running Linux microVMs on macOS (M1/M2)
Sometimes, while working on macOS, you may find the need to test something quick on Linux, or use some utility that’s only available on this OS. But, of course, you don’t want to go through all the process of creating the VM from scratch.
The good news is, you don’t need to! Using krunvm you can create and start a microVM from a regular container image (that is, an OCI image), in just two commands and a couple of seconds.
Installing krunvm on macOS
If you’re already using Homebrew, getting krunvm installed is super easy:
|
|
Creating a volume for krunvm
The first time you execute krunvm, you’ll get this message:
|
|
krunvm uses virtio-fs to share files between macOS and the Linux microVMs and, since Linux requires a case-sensitive file system, we need to create one on our system to be used to host the expanded container images.
Luckily, this is as simple as running the command suggested in the message:
|
|
Creating and starting your first microVM
Lets suppose you want to run a Debian microVM. As there are official Debian container images published on Docker Hub, this is as simple as running:
|
|
In this example, debian is the name of the container image used as source for the microVM, and debian-microVM is the name given to the microVM itself. Instead of debian you can use the name of any container, the same way you would when running a container with docker or podman. In this other example, the container image is specified including the registry, the image name and the tag:
|
|
Once created, you can start the newly created microVM this way (it should take less than a second to start up!):
|
|
By default, krunvm will execute /bin/sh in the microVM, but you can run any other command present on it by specifying it in the command line:
|
|
In fact, you can also run non-interactive commands and pass additional arguments to them:
|
|
And, without any kind of configuration, the network is completely funtional, so you can start installing packages right away:
|
|
Sharing files with the microVM
krunvm allows you to share volumes from macOS with the Linux microVM
by using the -v/--volume
argument, which can be specified with both
the create
and the changevm
commands.
Let’s change the Debian microVM we’ve created before to give it access
to $HOME/Public
(macOS) through /Public
(Debian):
|
|
Exposing ports from the microVM to macOS
It’s also possible to run a service in the microVM and expose it to
the outside by using the -p/--port
, also available with both the
create
and changevm
.
Once again, let’s update our Debian microVM, this time to expose port 80 on the microVM to the port 8080 on macOS:
|
|
Final words
krunvm is just a simple CLI utility. The heavy lifting here is done by buildah, libkrun and the Hypervisor.framework
If you find it useful, or you have any suggestion, I’ll be happy to hear from you on Twitter or Mastodon. If you have found a bug, please consider creating an issue on GitHub.