LVM (Logical Volume Management)
Virtual devices may be easier to manage than physical devices, and can have capabilities beyond what the physical devices provide themselves. A Volume Group (VG) is a collection of one or more physical devices, each called a Physical Volume (PV). A Logical Volume (LV) is a virtual block device that can be used by the system or applications. Each block of data in an LV is stored on one or more PV in the VG, according to algorithms implemented by Device Mapper (DM) in the kernel.
To manage VGs:
vgdisplay
vgcreate
vgextend
vgreduce
vgs # list vgs
Manage PVs:
pvcreate
pvdisplay
pvmove
pvremove
pvs # see all physical volumes
All tools to manage LVs in:
ls -lF /sbin/lv*
lvcreate
lvremove
lvs # see all lvs
All LVM utilities are listed in:
man lvm
PV -> VG -> LV path:
/dev/$vg_name/$lv_name
Creating LVs
-
Create partitions on disk drives (using
fdisk /dev/sda
t
8e
option to change type to LVM) -
Create physical volumes from the partitions.
sudo pvcreate /dev/sda4
pvdisplay -
Create the VG.
sudo vgcreate -s 16 vg /dev/sda4
vgdisplay -v # provides vg, pv and lv -
Allocate LV from VG.
# if needed
sudo vgextend vg /dev/sda4
sudo lvcreate -L 50G -n mylvm vg
lvgdisplay -
Format LV
sudo mkfs -t ext4 /dev/vg/mylvm
-
Mount LV (and update
/etc/fstab
if needed)sudo mkdir /mylvm
sudo mount /dev/vg/mylvm /mylvm
echo "/dev/vg/mylvm /mylvm ext4 defaults 1 2" >> /etc/fstab
To remove:
sudo umount /mnt
sudo lvremove /dev/vg/mylvm
Resizing LVs
When expanding the size of an LV with a filesystem, we first need to expand the LV then the fs. When shriking an LV with a filesystem, we first need to shrink the fs and then the LV.
# the -r options resizes fs at the same time as the LV is changed
sudo lvresize -r -L 20 GB /dev/vg/mylvm
# or
sudo lvreduce -L 10G /dev/$vg/$lv
Reduce a VG:
sudo pvmove /dev/sda4
sudo vgreduce vg /dev/sda4
LVM Snapshots
Useful for backups, deploying VMs, app testings as the create an exact copy of the VG.
To create a snapshot:
sudo lvcreate -l 128 -s -n mysnap /dev/vg/mylvm
To make mount:
mkdir /mysnap
mount -o ro /dev/vg/mysnap /mysnap
To use and remove snapshot:
sudo umount /mysnap
sudo lvremove /dev/vg/mysnap