Setting Up LVM (Logical Volume Manager)

A post from dbpandit

Let's start with a question.
Q. Why Do we need LVM?

Ans - Let's say that we are running a database server with 100G of physical volume. After running for few months, That volume is about to get 100% utilised. Now, We have two options, Either :

1) Shutdown MySQL, Copy everything to a big disk, update mysql configuration to point to the new location and start it back again.
2) Setup a slave of your databaseMove to another database server, if you don't have a big downtime for your website.
3) Third option is to create logical volume using LVM and increase/shrink disk size online whenever required.

Let's Setup LVM and see some of its features :

Install LVM2

apt update && apt install LVM2  

Mark physical volume for LVM :

pvcreate /dev/xvdf  

Create volume group :

vgcreate vgpool /dev/xvdf  

Create logical volume with name as dbdisk1 and use volume group :

lvcreate -n dbdisk1 -L 190G vgpool  

My Disk size is 200 though, Left some space for lvm internal operations. Now, after doing fdisk -l, You'll see /dev/mapper/vgpool-dbdisk1.

Format and mount logical volume. Formatting this logical volume with xfs :

mkfs.xfs /dev/mapper/vgpool-dbdisk1  

Mount to /dbops

mount /dev/mapper/vgpool-dbdisk1 /dbops  

Now, Verify your disk by running df -h
Expected output would be like :

/dev/mapper/vgpool-dbdisk1  190G   33M  190G   1% /dbops

Add new volume to physical volume group :
pvcreate /dev/xvdg

Add new volume in existing volume group by running vgextend :
vgextend vgpool /dev/xvdg

Extended logical volume to

lvextend -L+200G /dev/mapper/vgpool-dbdisk1  
  • Here, I have added new disk of size : 200G

Verify disk extension using : vgdisplay

Now, Extend logical volume :

xfs_growfs /dev/mapper/vgpool-dbdisk1  

Verify using df -h
Expected output :

/dev/mapper/vgpool-dbdisk1  390G   33M  390G   1% /dbops

Shrink Logical Volume in 3 steps :
1) Shrink file system.

2) Remove Volume from LogicalVolume :

lvreduce -L-200G /dev/mapper/vgpool-dbdisk1  

3) Remove volume from VolumeGroup :

vgreduce vgpool /dev/xvdg  

Drop logical Volume :

In Order to drop logical Volume, You have to first unmount logical volume :

umount /mnt/lvstuff  

Drop Logical Volume :

lvremove /dev/vgpool/lvstuff  

Drop Logical Group :

vgremove vgpool  

Drop physical volume which was marked initially for LVM :

pvremove /dev/sdb1 /dev/sdc1