Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Imperative Virtual Machines

In the imperative workflow, you define virtual machines under nixosConfigurations.<vm> in a flake, then use the microvm CLI to manage their lifecycle. See Imperative MicroVMs for the upstream option reference.

Define a Virtual Machine in a Flake

Note

Before continuing, make sure you’ve completed the Host Setup.

Add nix-mariner as a flake input, then define a nixosConfigurations.<vm> entry for your virtual machine.

The following flake.nix creates a VM named example:

{
  inputs.mariner.url = "github:mksafavi/nix-mariner";

  outputs =
    { mariner }:
    let
      nixpkgs = mariner.inputs.nixpkgs;
    in
    {
      nixosConfigurations.example = nixpkgs.lib.nixosSystem {
        system = "x86_64-linux";
        modules = [
          {
            imports = [ mariner.nixosModules.default ];
            mariner.cid = 4; # Unique per-VM CID that sets vsock number and IP address.
            mariner.ssh.authorizedKeys = [ "ssh-ed25519 AAAA... your@host" ]; # Replace with your ssh public key
          }
        ];
      };
    };
}

Calling microvm -c builds the VM and creates the systemd service for booting it.

sudo microvm -c example -f path:$(pwd)

Verify that the vm is created:

microvm -l

Either start the service:

sudo systemctl start microvm@example.service

Or start it in foreground:

sudo systemctl start microvm-virtiofsd@example.service
sudo microvm -r example

[vm@nixos:~]$ poweroff # To exit the Virtual machine.

microvm -r runs the VM directly instead of through systemd, if you are using virtiofs (default) for shared storage you need to start the virtiofsd service first.

You can now ssh into it:

ssh vm@vsock%4
# or:
ssh vm@10.0.0.4