# Linux as a virtualization guest

> Virtual machines, containers and cloud instances from the inside: guest drivers, images, what to reset when you clone, and cloud-init.

Source: https://aminbytes.dev/bytes/installation-and-packages/virtualization-guest/


Most Linux systems today don't run on bare metal. They run as virtual machines on a laptop, as instances in a cloud, or as containers on a server. Linux behaves a little differently there: it uses special drivers, it's often created from a copy of another system, and it gets configured automatically the first time it boots. If you clone a machine without knowing what makes it unique, you get subtle trouble later: duplicate addresses, confused logs, SSH warnings.

## Virtual machines

A **virtual machine (VM)** is a complete computer made in software: virtual CPU, memory, disk and network card. It runs its own kernel and operating system, the **guest**, on top of a real machine, the **host**. The software that makes this happen is the **hypervisor**:

- **Type 1 (bare metal):** runs directly on the hardware. Examples: KVM (built into the Linux kernel), Xen, VMware ESXi, Microsoft Hyper-V.
- **Type 2 (hosted):** an application on a normal OS. Examples: VirtualBox, VMware Workstation.

Modern CPUs have extensions that make this fast: Intel **VT-x** (CPU flag `vmx`) and AMD **AMD-V** (`svm`). Check a host with `grep -cE 'vmx|svm' /proc/cpuinfo`: anything above 0 means it's supported.

The guest can be **fully virtualized** (it thinks it's on real hardware and needs no changes) or **paravirtualized** (it knows it's virtual and talks to the hypervisor through special, faster drivers). In practice, most guests today are fully virtualized but use paravirtual drivers for disk and network.

Are you inside a VM right now? Ask systemd:

```bash
systemd-detect-virt
hostnamectl
```

```text
kvm
 Static hostname: web01
       Icon name: computer-vm
         Chassis: vm
      Machine ID: 3f2b9c0e8a1d4b7c9e6f5a4b3c2d1e0f
         Boot ID: 9a8b7c6d5e4f40312a1b2c3d4e5f6a7b
  Virtualization: kvm
Operating System: Debian GNU/Linux 12 (bookworm)
          Kernel: Linux 6.1.0-28-amd64
    Architecture: x86-64
```

`systemd-detect-virt` prints values like `kvm`, `vmware`, `oracle` (VirtualBox), `microsoft` (Hyper-V), `xen`, `docker`, `podman`, `lxc`, or `none` on real hardware.

## Containers

A **container** isolates a group of processes instead of emulating hardware. Containers on the same host **share the host's kernel**. The kernel gives each container its own view of the system with **namespaces** (its own process list, network, mount points, hostname) and limits its resources with **cgroups**. That's why a container starts in a second and can be a few megabytes in size.

There are two flavors:

- A **Linux container** (system container) behaves like a small whole system: it runs an init system, services and often SSH. Tools: LXC, LXD, Incus.
- An **application container** runs one application and what it needs, nothing else. Tools: Docker, Podman, and Kubernetes to run many of them.

| | Virtual machine | Linux (system) container | Application container |
| --- | --- | --- | --- |
| Kernel | Its own | Shared with the host | Shared with the host |
| Runs | A full OS | A full userland with init | One app (one main process) |
| Can run Windows on a Linux host? | Yes | No | No |
| Starts in | Tens of seconds | Seconds | Under a second |
| Examples | KVM, VirtualBox, VMware | LXC, LXD, Incus | Docker, Podman |

## Guest drivers and integration tools

A guest runs much better when it knows it's virtual. Hypervisors provide **guest drivers** and helper tools:

- **virtio** (KVM, QEMU and most clouds): paravirtual drivers in the mainline kernel. `virtio_net` for network, `virtio_blk` for disks (they show up as `/dev/vda`), `virtio_scsi`, and `virtio_balloon` to give memory back to the host.
- **qemu-guest-agent**: lets the host ask the guest to shut down cleanly, freeze filesystems for a backup snapshot, or report its IP addresses.
- **VirtualBox Guest Additions**: shared folders, a shared clipboard, automatic screen resizing, mouse integration and time sync.
- **open-vm-tools** (VMware Tools): the same kind of features for VMware.
- **Hyper-V** drivers (`hv_vmbus`, `hv_netvsc`, `hv_storvsc`) and Xen PV drivers ship with the kernel.

```bash
lsmod | grep -E 'virtio|vbox|vmw|hv_'
```

```text
virtio_net             69632  0
net_failover           20480  1 virtio_net
virtio_blk             24576  3
virtio_balloon         28672  0
```

Most distributions install the right tools automatically. If not, install packages like `qemu-guest-agent`, `open-vm-tools` or `virtualbox-guest-utils` with your package manager.

## Cloud instances (IaaS)

In **Infrastructure as a Service (IaaS)** clouds such as AWS, Azure, Google Cloud, Hetzner or OpenStack, you rent VMs by the hour. The building blocks are the same everywhere, with different names:

- **Compute instances:** the VMs themselves, sold in sizes (instance types) with a number of vCPUs and amount of RAM.
- **Block storage:** virtual disks (volumes) you create, attach to an instance, detach and resize. They outlive the instance. Some instances also have fast *ephemeral* storage that disappears when the instance stops.
- **Networking:** virtual networks and subnets, firewall rules (security groups), private addresses, and public or floating IPs that you attach to an instance.

You also pick an **image** to boot from and an SSH **key pair** to log in with. The instance learns its settings from a **metadata service**, usually at `http://169.254.169.254/`. (Side note: 169.254.0.0/16 is the link-local range: those addresses only exist on the local network segment. Clouds use it so every instance can reach its own metadata service at the same address.)

## Images, templates and clones

Nobody installs a cloud server from an ISO. You deploy from an **image**: a ready-made disk with an OS installed.

- **VM images** are disk files: `qcow2` (QEMU/KVM), `vmdk` (VMware), `vdi` (VirtualBox), `vhdx` (Hyper-V), or `raw`. An OVA/OVF bundles disks with the VM's hardware description. A **template** or *golden image* is an image you prepared once to clone many times.
- **Cloud images** are made for that: small, with cloud-init installed and no unique data inside. Every new instance is a fresh copy, often resized to the disk you chose.
- **Container images** (OCI format) are stacks of read-only layers stored in a registry like Docker Hub. `docker run debian` downloads the image and starts a container from it; many containers can share the same image.

### What makes a Linux system unique

A clone is an exact copy, including things that must be different on every machine. Reset these before or right after cloning:

| What | Where | Why it matters |
| --- | --- | --- |
| **SSH host keys** | `/etc/ssh/ssh_host_*_key` and `.pub` | They prove the server's identity. Shared keys let one clone impersonate another, and clients can't tell them apart. |
| **Machine ID** | `/etc/machine-id` | A unique ID systemd uses, for example for the journal folder `/var/log/journal/<id>/` and DHCP client IDs. Clones may even get the same IP address. |
| **D-Bus machine ID** | `/var/lib/dbus/machine-id` | The same ID for D-Bus. On most systems it's a link to `/etc/machine-id`; if it's a separate file, reset it too. |
| Hostname | `/etc/hostname` | Two machines with one name confuse people, logs and monitoring |
| Network identity | MAC addresses, static IPs, old udev rules like `/etc/udev/rules.d/70-persistent-net.rules` | Duplicate addresses, or a renamed network card that never comes up |
| Other | Shell history, logs, user keys, subscription or agent IDs | Leftover data and duplicate registrations |

Resetting them by hand:

```bash
# New SSH host keys
sudo rm /etc/ssh/ssh_host_*
sudo ssh-keygen -A                 # Debian also: sudo dpkg-reconfigure openssh-server

# New machine ID (and the D-Bus one, if it isn't a link)
sudo rm -f /etc/machine-id /var/lib/dbus/machine-id
sudo systemd-machine-id-setup
sudo dbus-uuidgen --ensure

# New hostname
sudo hostnamectl set-hostname web02
```

```text
ssh-keygen: generating new host keys: RSA ECDSA ED25519
Initializing machine ID from random generator.
```

For a **template**, empty the file instead of removing it: `sudo truncate -s 0 /etc/machine-id`. systemd sees an empty file as "first boot" and creates a new ID on the clone's first start. The `virt-sysprep` tool (from libguestfs) does all of this and more on a VM disk image in one command.

## cloud-init

**cloud-init** is the standard tool that turns a generic cloud image into *your* server on first boot. It reads **metadata** (instance ID, hostname, network) and **user data** (your instructions) from a datasource: the cloud's metadata service, a small config drive, or a local `NoCloud` ISO for VMs at home. Then it sets the hostname, creates users, installs SSH authorized keys, regenerates host keys, grows the root partition, installs packages and runs your commands.

User data is often a YAML file starting with `#cloud-config`:

```yaml {title="user-data"}
#cloud-config
hostname: web01
users:
  - name: deploy
    groups: sudo
    shell: /bin/bash
    sudo: "ALL=(ALL) NOPASSWD:ALL"
    ssh_authorized_keys:
      - ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... deploy@laptop
package_update: true
packages:
  - nginx
runcmd:
  - systemctl enable --now nginx
```

You paste this into the "user data" field when you create an instance. On the instance:

```bash
cloud-init status --wait            # wait until first-boot setup is done
sudo less /var/log/cloud-init-output.log
```

```text
status: done
```

Its own settings live in `/etc/cloud/cloud.cfg` and `/etc/cloud/cloud.cfg.d/`. Before turning a configured VM into a template, `sudo cloud-init clean` makes cloud-init run again on the next boot.

> [!TIP]
> To try cloud-init without a cloud account, Ubuntu's Multipass runs one with your user data: `multipass launch --cloud-init user-data`.

## Exam checklist

- A **VM** has its own kernel on virtual hardware, run by a hypervisor (type 1 like KVM, Xen, ESXi; type 2 like VirtualBox). Hardware support: `vmx` (Intel VT-x), `svm` (AMD-V).
- **Containers** share the host kernel, isolated with namespaces and cgroups. **Linux containers** (LXC) run a whole userland; **application containers** (Docker, Podman) run one app.
- **Guest drivers** and tools: virtio, qemu-guest-agent, VirtualBox Guest Additions, open-vm-tools. They bring speed, clean shutdown, time sync, shared folders and clipboard.
- IaaS building blocks: **compute instances**, **block storage** volumes, **networking** (virtual networks, firewalls, public IPs), plus images and SSH key pairs.
- Deploy from images: VM images (`qcow2`, `vmdk`), templates, cloud images and container images from a registry.
- After cloning, regenerate **SSH host keys** (`ssh-keygen -A`) and the **machine ID** (`/etc/machine-id`, **D-Bus** `/var/lib/dbus/machine-id`), and set a new hostname.
- **cloud-init** configures an instance on first boot from metadata and `#cloud-config` user data.
- `systemd-detect-virt` and `hostnamectl` tell you if, and how, you're virtualized.


## Byte check

1. You cloned a VM from a template. Which two things should you regenerate so the clone is truly unique?
   - **The SSH host keys and the machine ID (`/etc/machine-id`)** (correct)
   - The kernel and the initramfs
   - `/etc/passwd` and `/etc/group`
   Clones share the template's SSH host keys and machine ID. Duplicate host keys let one machine pose as another, and a shared machine ID confuses logging and DHCP.

2. What's the main difference between a container and a virtual machine?
   - **Containers share the host's kernel; VMs run their own kernel on virtual hardware** (correct)
   - Containers need hardware support like VT-x; VMs don't
   - Containers can only run one program; VMs can only run Linux
   A VM emulates a whole computer with its own kernel. A container is a group of isolated processes on the host kernel, which makes it smaller and faster to start.

3. What does cloud-init do?
   - **It configures a new instance at first boot from the cloud's metadata and user data** (correct)
   - It converts a VM image into a container image
   - It installs guest drivers for VirtualBox
   cloud-init reads data from the cloud (or a config drive) on first boot and sets the hostname, users, SSH keys, packages and commands.


