Kernel-based Virtual Machine (KVM) has become a cornerstone of Linux server virtualization, known for its maturity and performance. Red Hat’s decision to favor KVM over Xen starting with RHEL 6 solidified its position. This guide provides a detailed, step-by-step walkthrough of installing and configuring KVM on CentOS 6.x, ensuring a smooth virtualization experience.

Introduction to KVM

KVM is a full virtualization solution for Linux on x86 hardware containing virtualization extensions (Intel VT or AMD-V). It transforms the Linux kernel into a hypervisor, allowing you to run multiple guest operating systems, or virtual machines (VMs), concurrently. This offers benefits such as server consolidation, resource optimization, and improved disaster recovery capabilities.

Preliminary Check: Verify Hardware Virtualization Support

Before proceeding with the KVM installation, it’s crucial to verify that your hardware supports virtualization. This can be done by checking the /proc/cpuinfo file for specific CPU flags.

$ egrep -i 'vmx|svm' --color=always /proc/cpuinfo
  • vmx: Indicates Intel Virtualization Technology.
  • svm: Indicates AMD Virtualization.

If either “vmx” or “svm” is present in the output, your hardware supports virtualization and you can proceed. If not, KVM installation will not be possible on the current hardware.

Disable SELinux

SELinux (Security-Enhanced Linux) can sometimes interfere with KVM and libvirt operations. While it’s possible to configure SELinux to work with KVM, disabling it simplifies the initial setup process.

Warning: Disabling SELinux reduces system security. Consider re-enabling and configuring SELinux after you’ve successfully installed and configured KVM.

# To disable SELinux on CentOS:
$ sudo -e /etc/selinux/config

Modify the SELINUX line in the /etc/selinux/config file:

SELINUX=disabled

After saving the changes, reboot your server for the changes to take effect.

$ sudo reboot

Install KVM, QEMU and Required Packages

This section covers the installation of the necessary packages for KVM virtualization.

Install KVM, QEMU and User-Space Tools

Use the yum package manager to install KVM, libvirt (the virtualization management API), python-virtinst (for creating VMs from the command line), and qemu-kvm (the emulator):

$ sudo yum install kvm libvirt python-virtinst qemu-kvm

Start libvirtd Daemon and Set to Auto-Start

The libvirtd daemon manages virtual machines. Start the daemon and configure it to start automatically at boot:

$ sudo service libvirtd start
$ sudo chkconfig libvirtd on

Verify KVM Installation

Use the virsh command-line tool to verify that KVM has been installed successfully:

$ sudo virsh -c qemu:///system list

If KVM is running correctly, the output will show an empty list of VMs, indicating that the hypervisor is ready.

 Id    Name                           State
----------------------------------------------------

Alternative Installation using Group Install (Optional)

Alternatively, you can use yum groupinstall to install related virtualization packages:

$ sudo yum groupinstall "Virtualisation Tools" "Virtualization Platform"
$ sudo yum install python-virtinst

This installs a broader set of virtualization-related tools and libraries.

Configure Linux Bridge for VM Networking

By default, KVM VMs are isolated from the host system and the external network. To enable network connectivity, you need to configure a Linux bridge.

Install bridge-utils

Install the bridge-utils package, which provides tools for creating and managing bridge devices:

$ sudo yum install bridge-utils

Disable Network Manager and Enable Network Service

Network Manager can conflict with bridge configurations. Disable it and enable the traditional network service:

$ sudo service NetworkManager stop
$ sudo chkconfig NetworkManager off
$ sudo chkconfig network on
$ sudo service network start

Create the Bridge Interface (br0)

This involves modifying the network configuration files to create a bridge interface and assign your existing network interface (e.g., eth0) to it.

Important: Incorrect bridge configuration can lead to network connectivity loss. Ensure you have console access or a reliable out-of-band management solution before proceeding.

  1. Configure eth0: Modify the ifcfg-eth0 file to attach it to the bridge:

    sudo vim /etc/sysconfig/network-scripts/ifcfg-eth0
    

    Add the following line:

    BRIDGE=br0
    

    Ensure other settings like IPADDR, NETMASK, and GATEWAY are removed from this file. NM_CONTROLLED should be set to "no". The ONBOOT parameter should be set to "yes"

    DEVICE="eth0"
    NM_CONTROLLED="no"
    ONBOOT="yes"
    TYPE="Ethernet"
    BRIDGE=br0
    
  2. Create br0 Configuration: Create a new configuration file for the bridge interface:

    sudo vim /etc/sysconfig/network-scripts/ifcfg-br0
    

    Add the following lines, replacing the IP address, netmask, and gateway with your network’s settings:

    DEVICE="br0"
    BOOTPROTO="static"
    NM_CONTROLLED="no"
    ONBOOT="yes"
    TYPE="Bridge"
    NETMASK=255.255.255.192
    IPADDR=10.10.18.36
    GATEWAY=10.10.18.1
    

    Make sure DEVICE, BOOTPROTO, and TYPE are correctly configured. NM_CONTROLLED should be set to "no". The ONBOOT parameter should be set to "yes"

  3. Restart Network Service: Restart the network service to apply the changes:

    $ sudo service network restart
    
  4. Verify Bridge Configuration: Use the ifconfig command to verify that the bridge interface has been created and configured correctly:

    [ahmed@zahmed-server ~]$ ifconfig
    

    The output should show the br0 interface with the assigned IP address, netmask, and gateway. eth0 should also be present and assigned to the br0 interface.

Install VirtManager: The Graphical Management Tool

VirtManager provides a user-friendly graphical interface for managing KVM virtual machines.

Install VirtManager

Install VirtManager and its dependencies using yum:

$ sudo yum install virt-manager libvirt qemu-system-x86 openssh-askpass

The openssh-askpass package allows VirtManager to prompt for passwords when connecting to remote servers.

Launch VirtManager Remotely with X11 Forwarding

To launch VirtManager remotely via SSH, you need to enable X11 forwarding.

$ sudo yum install xauth
$ sudo vim /etc/ssh/sshd_config

Uncomment or add the following line in /etc/ssh/sshd_config:

X11Forwarding yes

Restart the SSH daemon to apply the changes:

$ sudo service sshd restart

A wrapper script can help resolve authentication issues when launching VirtManager remotely.

$ sudo -e /usr/bin/vm

Add the following lines to the vm file:

#! /bin/bash
xauth list | while read line; do
    sudo -i xauth add $line
done
sudo -i virt-manager

Make the script executable:

$ sudo chmod +x /usr/bin/vm

Now, you can launch VirtManager remotely by running:

$ vm

Installing a VNC Server for Remote Access

VNC (Virtual Network Computing) provides a graphical desktop sharing system that allows you to remotely control the server’s GUI.

Initial VNC Server Installation

Install the necessary packages for VNC server functionality:

sudo su
yum groupinstall Desktop
yum install gnome-core xfce4 tigervnc-server

Configure the vncserver service to start automatically at boot:

chkconfig vncserver on

Adding a VNC User and Setting the VNC Password

Create a dedicated VNC user and set the VNC password:

[root@ahmed-server ~]# su - ahmed
[ahmed@ahmed-server ~]$ vncpasswd
Password: ******
Verify: ******
[ahmed@ahmed-server ~]$

Configure the VNC server to run for the specified user.

sudo vim /etc/sysconfig/vncservers

Uncomment and modify the lines as follows (replace “ahmed” with your desired username and adjust the geometry as needed):

VNCSERVERS="2:ahmed"
VNCSERVERARGS[2]="-geometry 1024x768"

Restart the VNC server:

[root@ahmed-server ~]# service vncserver restart

Logging in from a Remote Machine

Install a VNC viewer on your local machine (e.g., RealVNC, TightVNC). Connect to the server using the IP address and display number (e.g., 10.10.18.36:2). Use the VNC password you set earlier.

Screenshot of Successful VNC Connection

Screen Shot

Troubleshooting KVM and VirtManager Setup

a. X11 Connection Rejected:

If you encounter the following error when launching VirtManager remotely:

X11 connection rejected because of wrong authentication.
Traceback (most recent call last):
  File "/usr/share/virt-manager/virt-manager.py", line 383, in
    main()
  File "/usr/share/virt-manager/virt-manager.py", line 286, in main
    raise gtk_error
RuntimeError: could not open display

Ensure you’re using the wrapper script (vm) to launch VirtManager, as described above.

b. D-Bus Error:

If you see the following D-Bus error:

D-Bus library appears to be incorrectly set up; failed to read machine
uuid: UUID file '/var/lib/dbus/machine-id'

Run the following command and reboot the host machine:

$ sudo sh -c 'dbus-uuidgen > /var/lib/dbus/machine-id'

c. Font Issues:

If you experience font issues while running VirtManager, install the following font package and relaunch it:

$ sudo yum install dejavu-lgc-sans-fonts

Upgrade CPU/RAM in KVM Virtual Machines

You can adjust the CPU and RAM allocated to a KVM virtual machine after it has been created.

  1. Edit the VM Configuration: Use the virsh edit command to modify the VM’s XML configuration:

    sudo virsh edit <vm-name>
    
  2. Modify CPU and Memory Settings: Locate the <memory> and <vcpu> elements and change their values accordingly. The <memory> element’s value is in KiB.

  3. Reboot the VM: Reboot the virtual machine for the changes to take effect.

Listing Virtual Servers

Use the virsh list command to view a list of running virtual machines:

[ahmed@ahmed-server ~]$ sudo virsh list
 Id    Name                           State
----------------------------------------------------
 8     VM-1                           running
 12    VM-2                           running
 13    VM-3                           running
 15    VM-4                           running

Getting Information About a VM

Use the virsh dominfo command to retrieve detailed information about a specific VM:

[ahmed@ahmed-server ~]$ sudo virsh dominfo VM-1
Id:             8
Name:           VM-1
UUID:           588ff640-25be-9b18-5eb3-f93c471848e6
OS Type:        hvm
State:          running
CPU(s):         4
CPU time:       503.3s
Max memory:     8388608 KiB
Used memory:    8388608 KiB
Persistent:     yes
Autostart:      disable
Managed save:   no
Security model: none
Security DOI:   0

Editing Hardware Configuration for a VM

You can directly edit the XML configuration file for a VM to modify its hardware settings.

[ahmed@ahmed-server ~]$ sudo virsh edit VM-1

The XML configuration file will open in your default text editor. Here’s an example of how to modify the memory and CPU allocation:

Before:

<domain type='kvm'>
  <name>VM-1</name>
  <uuid>588ff640-25be-9b18-5eb3-f93c471848e6</uuid>
  <memory unit='KiB'>8388608</memory>
  <currentMemory unit='KiB'>8388608</currentMemory>
  <vcpu placement='static'>4</vcpu>
  <os>
    <type arch='x86_64' machine='rhel6.5.0'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
    <apic/>
    <pae/>
  </features>
  ...
  ...
</domain>

After:

<domain type='kvm'>
  <name>VM-1</name>
  <uuid>588ff640-25be-9b18-5eb3-f93c471848e6</uuid>
  <memory unit='KiB'>33554432</memory>
  <currentMemory unit='KiB'>33554432</currentMemory>
  <vcpu placement='static'>8</vcpu>
  <os>
    <type arch='x86_64' machine='rhel6.5.0'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
    <apic/>
    <pae/>
  </features>
  ...
  ...
</domain>

In this example, the memory is increased to 32GB (33554432 KiB) and the number of virtual CPUs is increased to 8.

After saving the changes, restart the virtual machine.

Checking VM Information After Modification

After modifying the VM configuration, use virsh dominfo to verify the changes:

[ahmed@ahmed-server ~]$ sudo virsh dominfo VM-1
Id:             -
Name:           VM-1
UUID:           588ff640-25be-9b18-5eb3-f93c471848e6
OS Type:        hvm
State:          shut off
CPU(s):         8
Max memory:     33554432 KiB
Used memory:    33554432 KiB
Persistent:     yes
Autostart:      disable
Managed save:   no
Security model: none
Security DOI:   0

Optimizing VM Network Interface Performance

By default, KVM VMs might use a network interface with limited transmission speed. This section explains how to optimize the network interface for better performance.

virtio is a paravirtualized driver that can provide near-native network performance. e1000 emulates an Intel E1000 network card, which is generally slower than virtio but might be more compatible with some guest operating systems.

User commands below to change configuration on KVM.

sudo virsh edit <vm_name>
sudo virsh edit VM-1

This will open the XML configuration file for the specified VM.

Change the interface configuration by adding the <model type='virtio'/> element within the <interface> section:

<interface type='bridge'>
  <mac address='52:54:00:60:08:62'/>
  <source bridge='br0'/>
  <model type='virtio'/>
  <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>

Reboot the VM for the changes to take effect.

More details can be found here: https://help.ubuntu.com/community/KVM/Networking#_virtio

Adding a New Hard Disk to a Virtual Machine

This section describes the process of adding a new virtual hard disk to an existing KVM virtual machine.

  1. Create a disk image using qemu-img.
  2. Attach the image to the VM as a virtio disk.
  3. Format the new disk inside the VM.
  4. Add an entry to /etc/fstab to automatically mount the disk at boot.

Create a Disk Image Using qemu-img

Use the qemu-img create command to create a new disk image file.

[ahmed@ahmed-server ~]# qemu-img create -f raw VM-1-NEW-HDD.img 100G

This command creates a raw disk image named VM-1-NEW-HDD.img with a size of 100GB. The -f raw option specifies the raw disk image format, which generally offers the best performance.

Attach the Image to the VM as a virtio HDD

There are two methods for attaching the new disk image to the virtual machine: using VirtManager or using the virsh command-line tool.

Method 1: Adding the Image from the VirtManager UI

  1. Open VirtManager and select the VM you want to modify.
  2. Right-click on the VM and select “Open”.
  3. In the VM window, select “View” -> “Details”.
  4. Click on “Add Hardware”.
  5. Select “Storage” as the device type.
  6. Choose “Create a disk image to use as storage” or “Select managed or other existing storage”.
  7. Browse to the location of the disk image you created earlier.
  8. Set the “Device Type” to “virtio”.
  9. Set the “Storage Format” to “raw”.
  10. Click “Finish”.

'Adding New HDD'

After adding the HDD, you should see it listed in the VM’s hardware details.

'After Adding HDD'

More information can be found here: http://unix.stackexchange.com/questions/92967/how-to-add-extra-disks-on-kvm-based-vm

Method 2: Adding the Image Using the virsh Command

  1. Edit the VM configuration using the virsh edit command:

    [ahmed@ahmed-server ~]# virsh edit VM-1
    
  2. Add the following XML snippet to the <devices> section of the VM’s configuration file, replacing /virtual_machines/images/VM-1-ADD.img with the actual path to your disk image:

    <disk type='file' device='disk'>
      <driver name='qemu' type='raw' cache='none'/>
      <source file='/virtual_machines/images/VM-1-ADD.img'/>
      <target dev='vda' bus='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/>
    </disk>
    

    The target dev='vda' attribute specifies the device name that will be assigned to the disk inside the VM. The bus='virtio' attribute ensures that the virtio driver is used for optimal performance.

  3. Reboot the VM.

  4. After the VM restarts, you should see the new disk device.

     [ahmed@ahmed-server ~]# fdisk -l
    

'fdisk output'

Format the New Disk Inside the VM

Before you can use the new disk, you need to format it with a file system.

[ahmed@ahmed-server ~]# mke2fs -j /dev/vda

This command formats the /dev/vda device with the ext3 file system.

Add an Entry to /etc/fstab to Automatically Mount the Disk at Boot

To automatically mount the new disk at boot, add an entry to the /etc/fstab file.

# /etc/fstab
#
# Column Details here : http://man7.org/linux/man-pages/man5/fstab.5.html
# ------------------------------------------------------------------
/dev/vda        /data       ext3      defaults    0 0

Replace /data with the desired mount point for the new disk.

Now test by mounting all the devices mentioned in /etc/fstab:

[ahmed@ahmed-server ~]# mount -a

Check the mounted disks using the df -h command.

[ahmed@ahmed-server ~]# df -h

'DF OUTPUT'