Nixos-build-vms: access to the VM from host, and set different hostnames

I just created a simple VM using:

{
  test1 = {pkgs, config, ...}:
    {
      services.openssh.enable = true;
      networking.firewall.allowedTCPPorts = [ 80 22 ];
      services.nginx = {
        enable = true;
        virtualHosts."test1.example.org" = {
          default = true; # makes this the default vhost if no other one matches
          locations."/" = {
            root = pkgs.writeTextDir "index.html" "Hello world!";
          };
        };
      };
      nixpkgs.localSystem.system = "x86_64-linux";
      ## Does not work:
      # deployment.targetHost = "test1.example.net";

      # Other NixOS options
    };
}

and I run it with

$ nixos-build-vms test.nix
$ result/bin/nixos-run-vms

I have then qemu that is run, and it seems to pick some ip address:

test1 # [    9.950791] dhcpcd[575]: eth0: offered 10.0.2.15 from 10.0.2.2
test1 # [    9.954615] dhcpcd[575]: eth0: leased 10.0.2.15 for 86400 seconds
test1 # [    9.957658] dhcpcd[575]: eth0: adding route to 10.0.2.0/24
test1 # [    9.962456] dhcpcd[575]: eth0: adding default route via 10.0.2.2

however, I can’t ping this address from the host. I guess that qemu’s network is completely emulated here, so I’d be curious to know how to be able to make the VM accessible from the host.

Moreover, I’d like to be able to give a hostname (if possible several hostnames) to the VM, in order to be able to browse directly to the address test1.example.org from the host. Is it possible?

Thanks!

1 Like

Hi,
I’m just playing around with this, if anyone comes across this, hope it helps.
This allows me to see the http server “It Works” from my host.

Save the below as:
minimal.nix

{
  testvm = {pkgs, config, ...}:
    {
      nixpkgs.localSystem.system = "x86_64-linux";
      virtualisation.cores = 4;
      virtualisation.memorySize = 8192;
      virtualisation.forwardPorts = [
        { from = "host"; host.port = 8888; guest.port = 80; }
      ];


      networking.hostName = "test"; # Define your hostname.
      networking.firewall.enable = false;


      environment.systemPackages = with pkgs; [
        wget
      ];

      services.httpd.enable = true;

    };
}

Then run:

nixos-build-vms minimal.nix
./result/bin/nixos-run-vms

Now from your host you can use a browser to go to localhost:8888.

The key is looking at the virtualisation options which don’t include xen, vmware etc.

https://search.nixos.org/options?channel=22.11&from=0&size=500&sort=relevance&type=packages&query=virtualisation

1 Like