Linux lvm уменьшить размер

RootUsers

Guides, tutorials, reviews and news for System Administrators.

LVM Resize – How to Decrease an LVM Partition

Here we show you how to shrink an LVM volume or partition in Linux by first resizing the file system followed by resizing the logical volume.

See here if you’re instead trying to do the opposite and expand an LVM volume.

Note: In this example we are working in CentOS 7, some commands may differ in different Linux distributions. As of CentOS 7 the default file system is XFS which is not currently possible to shrink, this example is working with the ext4 file system.

In this example we will work through shrinking logical volume /var/centos/var from 10GB to 5GB.

Overview of Logical Volume Manager (LVM)

Before working through the resizing process it’s important you first understand some basic concepts around physical volumes, volume groups, logical volumes, and the file system.

  • Physical Volume (PV): This can be created on a whole physical disk (think /dev/sda) or a Linux partition.
  • Volume Group (VG): This is made up of at least one or more physical volumes.
  • Logical Volume (LV): This is sometimes referred to as the partition, it sits within a volume group and has a file system written to it.
  • File System: A file system such as ext4 will be on the logical volume.

LVM Resize – How to decrease or shrink the logical volume

To decrease the size of an LVM partition you must first decrease the file system within in order to avoid possible data corruption. As there is the potential for this to happen if you enter the command incorrectly, it is strongly recommended that you have a full backup of your data before proceeding. Shrinking a logical volume will give you more space in the volume group, meaning that you could instead extend another logical volume with this new found space.

The first step will depend on if you’re looking to shrink a LVM root volume, or non-root volume.

Shrinking a root volume

The root volume would typically be the logical volume that is mounted to /. You cannot unmount this to shrink it as it’s in use by the running operating system meaning that you will have to first boot from a Live CD to complete this. Once booted into the Live CD, you may first need to run the below command to pick up LVM volumes, however this usually happens during boot so may not be required, if in doubt just run it.

Shrinking a non-root volume

Alternatively if the volume you are shrinking is a non-root volume, that is any other volume not mounted to the root of the file system, you can unmount the volume as shown below to proceed. Please note that when you unmount the volume the data will not be available, so you may need to schedule down time and stop running applications that use data from it prior to unmounting. Unmount by specifying either the logical volume or the location it’s currently mounted to, in the below example we specify the logical volume which can be found in /dev/(vg-name)/(lv-name).

Читайте также:  Планирование задач at linux

All following steps now apply to both a root or non-root volume.

Before being able to attempt to shrink the size of an LVM volume, you must first run a file system check on it. If you don’t do this, you will get an error message and will not be able to proceed. This is a required step as resizing a file system in a bad state could cause data corruption. The -f flag makes the check run even if the file system appears clean, while -y assumes yes to all questions and will respond if asked to fix a problem.

Next you need to shrink the file system, to be safe we’re going to shrink the file system lower than what the logical volume will shrink to. This is because we don’t want to accidentally shrink the logical volume to a size lower than the file system in the next step, as this can result in corruption and data loss. Don’t worry, we’ll reclaim the space at the end.

The command below will shrink the file system so that it is only 4G in size total, note that what ever size you specify to shrink to you must have in free space within the file system otherwise you must first delete data.

resize2fs /dev/centos/var 4G

Once the file system has been reduced, we can shrink the size of the logical volume with the lvreduce command. Reduce this to the size that you want the volume to be, as specified by the -L flag. Instead if you want to reduce by a specified size, simply put a – in front of the size. Both are shown below for completeness, however you only need to run one.

lvreduce -L 5G /dev/vg/disk-name
lvreduce -L -5G /dev/vg/disk-name

Once you execute the lvreduce command you will get a warning advising the size you have chosen to reduce to so use this as a chance to confirm you’re shrinking the logical volume to a size that is NOT smaller than the size you previously shrunk the file system to. Once you have confirmed it’s fine to proceed enter ‘y’ and press enter.

After the logical volume has been lowered to the required size, run resize2fs on the volume as this will extend the file system to use all available space within the logical volume. This makes use of all remaining free space so that none is wasted from when we previously shrunk the file system to a lower size than the logical volume.

At this point all that’s left to do is mount the volume. If this was a root volume and you’re working within a Live CD, simply boot back into your primary Linux operating system.

If this was a non-root volume and you unmounted it to complete the reduction, simply mount it back. You can do this with ‘mount -a’ assuming you have the configuration already set in /etc/fstab, otherwise specify the logical volume and where it should mount to. Here we’re manually mounting to /mnt just for testing.

Читайте также:  Type команда в linux

After you’ve either booted back to primary operating system or completed the mount, check the space shown with the ‘df’ command to confirm it has been decreased as expected.

[[email protected] /]# df -h Filesystem Size Used Avail Use% Mounted on /dev/mapper/centos-root 9.8G 1.4G 8.5G 14% / devtmpfs 908M 0 908M 0% /dev tmpfs 914M 0 914M 0% /dev/shm tmpfs 914M 8.6M 905M 1% /run tmpfs 914M 0 914M 0% /sys/fs/cgroup /dev/sda1 497M 96M 402M 20% /boot /dev/mapper/centos-var 4.8G 20M 4.6G 1% /mnt 

In this example /dev/centos/var is correctly showing as shrunk down from the original 10G.

Summary

We have now successfully shrunk a file system and corresponding LVM logical volume. Root volumes can only be shrunk by unmounting the file system which requires booting into a Live CD to complete the work. For non-root volumes the file system must first be unmounted so that you can shrink the volume. First the file system was checked, then reduced. The logical volume itself was then reduced. It is strongly recommended to have a backup before attempting this to avoid data loss through mistakes.

Share this:

Источник

Изменение размера дисков LVM

На днях пришлось менять диски на сервере CentOS 6.7. Старые диски хоть и рабочие еще, но с нагрузкой не справлялись. Поэтому раскошелились и купили SSD диски такой же емкости, как и старые. Но т.к. стоимость 1 Гб на SSD диске намного дороже, то посмотрев на размер /var (180 Гб) и / (корневой раздел) 300 Гб, само собой напросилось решение увеличить размер / за счет уменьшения размера /var. Идея, конечно, хорошая, но раньше я никогда таким не баловался, поэтому провел выходные на форумах, проверил сначала все на виртуальной машине без raid, потом подумал, что на моем сервере работает софтовый raid1 и сделал тестовый стенд (на старый комп поставил CentOS 6.7 с двумя дисками в программном raid1) и проверил все на нем, потом уже выполнил повторно на рабочем сервере. Но все же волнительно было, чего уж. Итак, поехали!

Совет: если вы раньше никогда не развлекались изменениями разделов, никогда не пробуйте это делать на рабочем компьютере.

Итак, есть система из двух дисков, объединенных в raid1 (зеркало).

/dev/sda:
/dev/sda1 200 Мб, /dev/md0
/dev/sda2 480 Гб, /dev/md1

/dev/sdb:
/dev/sdb1 200 Мб, /dev/md0
/dev/sdb2 480 Гб, /dev/md1

На /dev/md1 тома LVM:
/dev/VolGroup/LogVol00 swap 2 Гб
/dev/VolGroup/LogVol01 /var 180 Гб, ext4
/dev/VolGroup/LogVol02 / 300 Гб, ext4

Для чего я привел пример разбивки? Чтобы вы обратили внимание, что мы в дальнейшем ни разу не будем ресайзить тома на устройствах /dev/sdXY. Мы все изменения разделов будем проводить только с логическими томами LVM!

Задача: изменить размер /var до 30 Гб и отдать все освободившееся место в / (корень). Файловая система обоих разделов ext4. Система CentOS 6.7.

Шаг 1: уменьшаем /var

В моем случае (софтовый raid1) я сначала проверил на всякий случай, что все диски подключены и ошибок нет (cat /proc/mdstat).

Я не был уверен, что размонтировать /var (umount /var) в рабочем режиме хорошая мысль, поэтому загрузился с LiveCD CentOS в Rescue Mode (можно было войти в single mode и без LiveCD).

Читайте также:  Linux сменить группу владельца папки

Проверяем доступность физического тома LVM:

# pvscan
PV /dev/md1 VG VolGroup lvm2 [480.00 GiB / 0 free]

Проверяем доступность групп томов:

# vgscan
Reading all physical volumes. This may take a while.
Found volume group «VolGroup» using metadata type lvm2

Активируем логические тома:

# lvscan
ACTIVE ‘/dev/VolGroup/LogVol01’ [180.00 GiB] inherit
ACTIVE ‘/dev/VolGroup/LogVol00’ [2.00 GiB] inherit
ACTIVE ‘/dev/VolGroup/LogVol02’ [300.00 GiB] inherit

Можно посмотреть подробности тома /dev/VolGroup/LogVol01 (он у нас /var):

Все вышеуказанные проверки служат для того, чтобы вы были уверены, что тома LVM видны и активны и чтобы вы понимали, с каким именно томом вам следует проводить дальнейшие дествия. Идем дальше.

Отмонтируем том, который у нас /var и который будет уменьшать:

Выполняем проверку файловой системы тома:

Команда должна пройти без ошибок.

Выполняем проверку на наличие ошибок (-f — force):

# e2fsck -f /dev/VolGroup/LogVol01

Сначала уменьшаем размер файловой системы тома:

resize2fs -p /dev/VolGroup/LogVol01 30G

Внимание: здесь «30G» — это размер, который мы хотим задать для файловой системы, а не на который мы хотим уменьшить файловую систему.

И только после этого изменяем размер тома LVM:

# lvreduce -L 30G /dev/VolGroup/LogVol01

Получили сообщение об успешном завершении.

Теперь можно и не монтировать обратно раздел, а сразу перезагрузиться и проверить, что все ок, система загружается, df -h выдает размер /var равным 30 Гб.

На CentOS после загрузки до входа в систему появилось сообщение от SELinux, который должен переиндексировать изменения. Ок. Это заняло какое-то время и система сама перезагрузилась. После этого я вошел в систему и убедился, что все ок. Только после этого я перешел ко второму шагу (который оказался намного быстрее и проще), а именно увеличению корневого раздела путем добавления к нему всего доступного свободного места на физическом томе LVM. Заупстите pvscan и посмотрите, в выводе команды будет указано, есть доступное место (это плюс-минус то, что было занято раньше под /var). Теперь мы это свободное место добавим к / (корню).

Шаг 2: увеличиваем размер тома LVM (который у нас / ) без перезагрузки

Да, вы не очитались. Чтобы увеличить размер тома LVM нам не придется загружаться в single mode (или через LiveCD в Rescue mode).

На всякий случай, чтобы не перепутать, какому тому вы хотите отдать свободное место, выполните cat /etc/fstab и lvscan, убедитесь, что раздел / (корень) — это /dev/VolGroup/LogVol02, а не что-то иное 😉

Именно так, без пробелов между -l (это маленькая L) и +100%FREE. Заметьте, я не стал указывать, на сколько точно я хочу увеличть размер тома. В данной ситуации мне это было не нужно и чтобы не гадать, сколько конкретно надо добавить Гбайт, я просто указал, чтобы было добавлено все, что можно. man lvextend для ознакомления с вариациями -L+100G 😉 Опция -r указывает на то, чтобы был выполнен ресайз файловой системы после увеличения логического тома. Без этой опции команды было бы две:

# lvextend -l+100%FREE /dev/VolGroup/LogVol02
# resize2fs /dev/VolGroup/LogVol02

После успешного завершения я бы перезагрузился и проверил, что все ок.

Естественно, все вышеописанное может дать сбой на любом этапе, хотя бы из-за сбоя электропитания. Поэтому если данные на изменяемых разделах хоть как-то важны, вы должны иметь их копию.

Все вышеперечисленное верно для CentOS. Для Ubuntu вроде бы все то же самое. Думаю (не знаю) что для всех современных Linux все команды такие же.

Авторизуйтесь для добавления комментариев!

Источник

Оцените статью
Adblock
detector