LVM Usage

Aug 17, 2019 usage article

Concept

TL;DR

If you get a new disk, and want to use it as lvm:

  1. use fdisk to partite that disk
  2. use pvcreate to create pv
  3. use vgcreate to create new vg (or vgextend to add pv to an exist vg)
  4. use lvcreate to create new lv (or lvresize to extend a exist lv)
  5. use mkfs.ext4 to create fs on lv
  6. use mount to mount lv, and update /etc/fstab to auto mount

PV

Each pv (Physical Volume) needs a pm(Physical Media). pm can be the entire disk(/dev/sda) or a partitioned disk(/dev/sda1).

So you can create a pv on a new disk just using pvcreate:

$ pvcreate /dev/sdb

Or you can use fdisk to partite the disk and create pv on it:

$ fdisk /dev/sdb
  • p ↵Enter watch and validate your sequence is gonna be correct
  • n ↵Enter
  • ↵Enter ↵Enter ↵Enter ↵Enter create new primary part with all defaults
  • t ↵Enter ↵Enter 8 e ↵Enter change type of part2 to LVM
  • w ↵Enter save and exit
$ pvcreate /dev/sdb1

List all pv with pvs

$ pvs

I perfer to the second one. no special reason, just regular usage.

another case is you may already have an exist pv and extended the partition. so from parted -l you can see the disk has been extened:

Model: Virtio Block Device (virtblk)
Disk /dev/vda: 107GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:

Number  Start   End     Size    Type     File system  Flags
 1      1049kB  1075MB  1074MB  primary  xfs          boot
 2      1075MB  107GB   106GB   primary               lvm

but not in pvs:

  PV         VG     Fmt  Attr PSize   PFree
  /dev/vda2  centos lvm2 a--  <19g    0

in that case, you need to use pvresize:

pvresize /dev/vda2

VG

Once you get pv, you can create vg(Volume Group) on it.

$ vgcreate vg_1 /dev/sdb1

If you want to add pv to an exist vg:

$ vgextend vg_1 /dev/sdb1

LV

Next we can craete lv on vg:

$ lvcreate -L 50G -n lv_1 vg_1

Or resize lv:

$ lvresize -L +20G /dev/vg_1/lv_1
$ lvresize -L -20G /dev/vg_1/lv_1

# Sync the size info to fs
$ resize2fs /dev/vg_1/lv_1
# if you got error like
# resize2fs: Bad magic number in super-block while trying to open /dev/vg_group/lvname, then use xfs_growfs instead
$ xfs_growfs /dev/vg_1/lv_1


# Resize SWAP in LVM
$ swapoff -a
$ lvresize -L +2G /dev/vg_1/swap_lv
$ mkswap /dev/vg_1/swap_lv
$ swapon -a

Or remove lv:

$ umount /dev/vg_1/lv_1
$ lvremove /dev/vg_1/lv_1
# Comment the line /etc/fstab, such as
# /dev/vg_1/lv_1 /lv_1  xfs ...