How to use KVM/QEMU from the Terminal

KVM (Kernel-based Virtual Machine) is a full virtualization solution for Linux on x86 hardware, and QEMU is a machine emulator and virtualizer that can perform hardware virtualization. Together, KVM and QEMU allow you to create and run virtual machines on your Linux system from the terminal.

Here’s how to get started with KVM/QEMU:

  1. Install Required Packages

First, you’ll need to install the required packages. On Ubuntu or Debian, run:

Bash
sudo apt install qemu-kvm libvirt-clients libvirt-daemon-system virt-manager
Bash

On CentOS or RHEL:

Bash
sudo yum install qemu-kvm libvirt virt-install virt-viewer virt-manager
Bash
  1. Check if KVM is Enabled

To verify if KVM is enabled on your system, run:

Bash
lscpu | grep -i virtualization
Bash

If the output shows VMX or AMD-V, then your CPU supports hardware virtualization.

  1. Create a Virtual Machine

To create a new virtual machine, use the virt-install command. Here’s an example for creating an Ubuntu 20.04 VM:

Bash
virt-install --name ubuntu2004 --ram 2048 --disk path=/var/lib/libvirt/images/ubuntu2004.qcow2,size=20 --vcpus 2 --os-type linux --os-variant ubuntu20.04 --network network=default --graphics none --console pty,target_type=serial --location 'http://archive.ubuntu.com/ubuntu/dists/focal/main/installer-amd64/' --extra-args 'console=ttyS0,115200n8 serial'
Bash

This creates a VM named ubuntu2004 with 2GB RAM, 2 vCPUs, a 20GB disk image, and installs Ubuntu 20.04 from the network.

  1. Manage Virtual Machines

Once you’ve created a VM, you can manage it using various virsh commands:

List all VMs:

Bash
virsh list --all
Bash

Start a VM:

Bash
virsh start ubuntu2004
Bash

Connect to the VM console:

Bash
virsh console ubuntu2004
Bash

Shut down a VM:

Bash
virsh shutdown ubuntu2004
Bash
  1. Networking

By default, QEMU/KVM VMs are connected to a virtual network called default. You can configure networking using virsh:

List networks:

Bash
virsh net-list --all
Bash
Edit a network:
Bash
virsh net-edit default
Bash

This opens the network XML in your default text editor, where you can modify settings like IP address range, forwarding modes, etc.

That’s a basic overview of working with QEMU/KVM from the terminal. With these tools, you can create and manage virtual machines for testing, development, or any other purpose right from your Linux command line.