Exposing Virtual Machines in KubeVirt

As with Pods, the real utility of running virtual machines in a Kubernetes cluster comes from exposing services outside the cluster. Services can be created using the virtctl tool to "expose" a virtual machine. The following guided exercise demonstrates this method.

Using virtctl to expose VM ports as Services

The virtctl expose command works much like the kubectl expose command, but on virtual machines. Here is an example of a Service produced by this process:

apiVersion: v1
kind: Service
metadata:
  name: testvm-http
  namespace: default
spec:
  ports:
  - port: 8080
    targetPort: 80
  selector:
    kubevirt.io/domain: testvm
    kubevirt.io/size: small
  type: NodePort

 

Pointing Services at VMs and Pods

A more general approach is to create Service objects within the cluster and use the Service's selector field to connect the service with endpoints like the VirtualMachineInstance's (VMI's) virt-launcher Pod. Labels to be used for Service selectors should be attached to the VMI by either setting them in the spec.template section of the parent VirtualMachine, or by using the kubectl label command to create the label on a running VMI. Labels set in a running VM will not take effect until the VM is stopped and restarted, but you can also directly label the virt-launcher Pod as any other Pod, just remember to make the label persist across restarts by adding it to the template in the VM as well.