How to create virtualbox VM from the console

Virtualbox is a nice option for virtualization. It can be controlled from both GUI and CLI. First option is usually used, but in some cases second is useful too. In this small guide we will create and configure one instance of virtual machine and launch it from CLI.

Installation

install virtualbox
apt-get install virtualbox

(optional) install missing linux headers if vboxheadless command raises an errors
apt-get install linux-headers-$(uname -r) build-essential

Register basic VM

set a name for the virtual machine
VM='vm01'

create and register virtual machine
vboxmanage createvm --name $VM --register

Set CPU count and memory size

set memory size and number of CPU cores.
vboxmanage modifyvm $VM --memory 1024 --cpus 1

(optional) enable ioapic, if you are installing Windows system with 2 or more CPU cores.
vboxmanage modifyvm $VM --ioapic on

Add virtual drives

create 20GB virtual disk
vboxmanage createhd --filename $VM.vdi --size 20480

create new IDE controller
vboxmanage storagectl $VM --name "IDE Controller" --add ide --controller PIIX4

attach virtual disk to the controller
vboxmanage storageattach $VM --storagectl "IDE Controller" --port 0 --device 0 --type hdd --medium $VM.vdi

attach .iso image with a system of your choice to the controller
vboxmanage storageattach $VM --storagectl "IDE Controller" --port 0 --device 1 --type dvddrive --medium /path/to/image.iso

Configure network options

(option 1) connect VM via bridge interface with eth0
vboxmanage modifyvm $VM --nic1 bridged --cableconnected1 on --bridgeadapter1 eth0

(option 2) connect VM via hostonly interface
vboxmanage modifyvm $VM --nic1 hostonly --cableconnected1 on --hostonlyadapter1 vbox0

(option 3) connect VM via NAT interface
vboxmanage modifyvm $VM --nic1 nat --cableconnected1 on

(option3) (optional) forward port through NAT
vboxmanage modifyvm $VM --natpf1 ,tcp,,3389,,3389

Enable remote access

download guest additions here
wget download.virtualbox.org/virtualbox/4.1.26/Oracle_VM_VirtualBox_Extension_Pack-4.1.26-84997.vbox-extpack

install guest additions
vboxmanage extpack install Oracle_VM_VirtualBox_Extension_Pack-4.1.26-84997.vbox-extpack

enable VM remote access via RDP (for installation)
vboxmanage modifyvm $VM --vrde on --vrdeport 3389

Run VM

run VM
vboxheadless --startvm $VM

(optional) run VM without blocking
nohup vboxheadless --startvm $VM &

Some administrative commands

shutdown virtual machine
vboxmanage controlvm $VM acpipowerbutton

insert disk with VirtualBox Guest Additions
vboxmanage storageattach $VM --storagectl "IDE Controller" --port 0 --device 1 --type dvddrive --medium VBoxGuestAdditions.iso

display virtual machine info
vboxmanage showvminfo $VM