How to install headless Ubuntu using kvm and CLI
Summary
While trying to create a new VM using KVM I kind of found it more difficult than expected, so here is a short tutorial on how I finally made it :)
This tutorial shows how to create a VM using KVM from the command line. The VM will be running a minimal Ubuntu 18.04 installation without a desktop environment. The whole process can be performed through ssh, so there is no need for openning any windows.
Creating the VM
To create a vm as described above you can use the following command:
sudo virt-install --name=ubuntu-vm-18.04 --vcpus=2 --cpu=host --memory=1024,maxmemory=4096 --disk size=10 --os-variant=ubuntu18.04 -l "http://gr.archive.ubuntu.com/ubuntu/dists/bionic/main/installer-amd64/" --network network:default --graphics none --extra-args='console=ttyS0,115200n8 serial'
The most important parameters for our mission are the -l
(short for
--location
) and the --extra-args
.
--extra-args
is mandatory to make kvm show us the VM's prompt, and
unfortunately it is not compatible with --cdrom
.
That said we can't use a local iso to create the VM, we need to do it using
netinst.
Additionally in order to be able to access the VM you need to make sure to install the OpenSSH server.
Accessing the VM
After the installation the VM will restart and you will see an empty screen.
To exit that screen press CTRL-SHIFT-]
.
Running sudo virtsh list
should show the new vm running.
Unfortunately though you won't be able to access the vm using sudo virtsh
console
yet.
We can however access it through ssh. To find the ip address of the VM we can use:
sudo virsh net-dhcp-leases default
Note that default
here matches the network that we passed to virt-install
when creating the VM.
Now using the IP you should be able to login through to the machine through ssh.
Have fun!
Enabling virtsh console
(Optional)
To enable access through the virtsh console
we need to edit
/etc/default/grub
and append console=ttyS0
to GRUB_CMDLINE_LINUX_DEFAULT
.
e.g.
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash console=ttyS0"
After that we need to update grub and restart the VM:
sudo update-grub
sudo reboot
When the VM gets up again we can use sudo virsh console ubuntu-vn-18.04
to
open the VM console.
Pressing enter will present the login prompt.
When done, after logging out we can use CTRL-SHIFT-]
to exit the console.
Note that the VM will keep running, to shut it down issue sudo virsh shutdown
ubuntu-vm-18.04
and to start it up again issue sudo virsh start
ubuntu-vm-18.04
.