- How to resize a logical volume with 5 simple LVM commands
- Process summary
- Create a Physical Volume
- Identify the Volume Group
- Extend the Volume Group
- In the cloud
- Identify the Logical Volume
- Extend the Logical Volume
- Extend the filesystem
- Wrap up
- Изменение размеров разделов LVM
- 12 thoughts on “ Изменение размеров разделов LVM ”
- Расширение диска или раздела Linux
- Шаг 1. Расширение раздела
- Обычные тома
- Шаг 2. Изменение размера для файловой системы
- Увеличение разделов с Gparted
- RootUsers
- Guides, tutorials, reviews and news for System Administrators.
- LVM Resize – How to Decrease an LVM Partition
- Overview of Logical Volume Manager (LVM)
- LVM Resize – How to decrease or shrink the logical volume
- Shrinking a root volume
- Shrinking a non-root volume
- Summary
How to resize a logical volume with 5 simple LVM commands
Posted: April 21, 2021 | by Shehu Awwal
Have you ever wondered how to extend your root or home directory file system partition using LVM? You might have low storage space and you need to increase the capacity of your partitions. This article looks at how to extend storage in Linux using Logical Volume Manager (LVM).
Process summary
The process is straightforward. Attach the new storage to the system. Next, create a new Physical Volume (PV) from that storage. Add the PV to the Volume Group (VG) and then extend the Logical Volume (LV).
Look at the picture below. The red line mark shows the original size of the root mount point. The xvdc disk is the new disk attached to it. Extend the root partition to make it 60G in size.
Create a Physical Volume
When you attach the new storage /dev/xvdc , you need to use the pvcreate command in order for the disk to be initialized and be seen by the Logical Volume Manager (LVM).
Identify the Volume Group
Next, you need to identify the Volume Group (VG) to which you are extending the new disk with the vgs command. Mine is called centos, and that’s the only VG available currently on my LVM.
Extend the Volume Group
The vgextend command allows you to add one or more initialized Physical Volumes to an existing VG to extend its size.
As you can see, you want to extend the centos Volume Group.
After extending it, type the vgs or vgdisplay commands for a more detailed overview of the VG.
The vgs command shows only the VG in with a few lines.
The vgdisplay shows all the VGs in the LVM and displays the complete information about them.
In the cloud
As you can see from the image above, marked with red, you have 10GB free. You can decide to extend all or some amount of storage size to it.
Identify the Logical Volume
The lvs or lvdisplay command shows the Logical Volume associated with a Volume Group. Use the lvs command, and the Logical Volume you’re trying to extend is the root, which belongs to the centos VG. As you can see above, you’ve already extended the VG. Next, extend the Logical Volume.
Extend the Logical Volume
Extend the LV with the lvextend command. The lvextend command allows you to extend the size of the Logical Volume from the Volume Group.
Extend the filesystem
You need to confirm the file system type you’re using, Red Hat uses the XFS file system, but you can check the file system with lsblk -f or df -Th .
Resize the filesystem on the Logical Volume after it has been extended to show the changes. Resize the XFS filesystem by using the xfs_growfs command.
Finally, verify the size of your extended partition.
Wrap up
You can extend any other partition with the steps shown. You just have to ensure you’re using LVM and know the partition you’re extending. If you want to learn more about LVM, check out other articles from Enable Sysadmin by searching LVM.
Источник
Изменение размеров разделов LVM
Некоторые установщики Linux создают большой раздел /home, если для системных служб необходимо больше места на разделе / (root), можно изменить конфигурацию LVM разделов без перезагрузки сервера.
До изменений раздел / (root) заполнен на 98%, и имеются свободные 141GB на партиции /home
1. Отмонтируем раздел /home
Для успешного отключения раздела, остановите сервисы работающие на нем, а также выйдите из системы всеми пользователями кроме root
2. Уменьшаем размер раздела /home до 20GB, (Система попросит провести проверку тома коммандой e2fsck)
3. Уменьшаем LVM том /dev/mapper/vg_oracle-lv_home до 20G
4. Расширяем LVM том /dev/mapper/vg_oracle-lv_root до максимально возможного размера.
5. Увеличиваем раздел /root (ext3/4) используя все свободное место.
6. Монтируем /home
Теперь в корневом разделе сервера 72% свободного места.
TL;DR
Уменьшение раздела /home (/dev/mapper/vg_oracle-lv_home) до 20GB и перенос свободного места в корневой раздел диска /root (/dev/mapper/vg_oracle-lv_root):
12 thoughts on “ Изменение размеров разделов LVM ”
Your heading «_online_ resize…» is misleading because your first
(and necessary) step is unmounting /home.
Online shrinking of LVM partitions is not possible.
I stumbled over this page because I saw «online» and «shrink»
and thought «Oooh something new I have missed something».
🙂 Olaf
sorry for confusion, I agree it is partially online — at least you don’t need to unmount root 🙂
Firstly, thanks for the information. Worked perfect for me and now have plenty of room to store under /root folder. Probably would of been easier for me to set the partitions correctly when I installed fedora but hey no-ones perfect…
Had all sorts of trouble trying to do this on my system to start with because I was logged in.
Recommend to all to use rescue mode boot from usb/cd. This ensured no users being logged in and no files being used in /home directory. Also means you don’t have to carry out ‘lazy’ umount on /home.
Thank you very much,
just resized my filesystem with no issues.
Worked perfectly for me. Thanks for putting this up!
I cannot unmount my /home. It says «device is busy». How do I deal with this
This is common error, try following:
1. change your directory to something not /home (cd /root)
2. check who is logged in to the box by running who, ask them to log off/ kill their pts process (ps -dN|grep pts/3)
3. if you have services running from home, stop them
perfect documents sucessfully shirnk home partition and increase root on centos 6.5
I have applied this in my Centos (2.6.32-431.29.2.el6.x86_64) server and it works fine !!
It worked flawlessly on OEL 6.8.Thanks for the excellent tip
I closely followed the instructions, but have an issue after step 2.
I successfully (without errors) ran
e2fsck -f /dev/my_home
resize2fs /dev/my_home 426G
The initial size of /home was 436G, so I tried to reduce by about 10G. I still had about 40G free space in /home.
When I want to run
lvreduce -L 426G /dev/my_home
I obtain an error that the location does not exists. Checking with
df
shows that /dev/my_home does not exist anymore. Any idea what happened?
Источник
Расширение диска или раздела Linux
В инструкции рассмотрены сценарии расширения дискового пространства разделов в Linux без потери информации.
Принцип увеличения диска:
- Расширение раздела.
- Изменение размера файловой системы.
В зависимости от типа раздела и файловой системы, действия различаются.
Любая работа с диском несет риск потери информации. Перед началом работ убедитесь в наличие резервных копий ценных данных.
Шаг 1. Расширение раздела
Обычные тома
Допустим, есть диск /dev/sdb и раздел /dev/sdb2, который нужно увеличить.
Сначала необходимо отмонтировать раздел:
В случае работы с корневой директорией, отмонтировать ее не получиться. В таком случае необходимо загрузить компьютер с LiveCD.
Подключаемся утилитой fdisk к /dev/sdb:
Если мы работаем с разделом более чем 2Тб, используем утилиту parted.
Смотрим номера разделов:
Удаляем раздел (не переживайте — все данные сохраняются):
* в моем примере, раздел для удаления на второй позиции.
Создаем новый раздел:
Номер раздела — 2:
На запрос начального и конечного секторов просто нажимаем Enter.
Если раздел был загрузочный, добавляем соответствующий флаг:
Еще раз проверяем, что получилось:
LVM-тома расширяются на лету, даже для корневых разделов. В данном примере, работаем с /dev/sda.
Открываем диск утилитой fdisk:
* напомню, что при работе с диском 2Тб и более, следует использовать утилиту parted.
Создаем еще один раздел:
Номер раздела оставляем тот, который предлагает система (просто нажимаем Enter).
Первый и последний сектора также оставляем по умолчанию для использования всего дискового пространства (еще два раза Enter).
Задаем тип раздела:
Выбираем номер раздела (в моем примере создавался раздел 3):
Командой L можно посмотреть список всех типов, но нас интересует конкретный — LVM (8e):
Проинформируем систему, что в таблице разделов произошли изменения:
Создаем физический том из нового раздела:
Смотрим наши Volume Group и для нужного добавляем созданный том:
vgextend vg_centos /dev/sda3
* в моем примере группа томов LVM называется vg_centos
Смотрим LVM-разделы и расширяем пространства для нужного:
lvextend -l +100%FREE /dev/vg_centos/lv_root
* данная команда расширяем LVM-раздел /dev/vg_centos/lv_root, используя все свободное пространство (100%FREE).
Шаг 2. Изменение размера для файловой системы
После того, как на предыдущем шаге мы расширили раздел, система по-прежнему будет видеть старый по объему диск. Чтобы это исправить, необходимо выполнить команду по изменению размера файловой системы. В зависимости от последней, команды различаются.
Посмотреть файловую систему:
ext2/ext3/ext4:
XFS:
Reiserfs:
* обратите внимание, что в данных примерах используются различные устройства.
Если раздел был отмонтирован, монтируем его, например:
mount /dev/sda2 /mnt
Проверяем, что настройки применились:
Увеличение разделов с Gparted
Если работы выполняются на системе с графическим интерфейсом или есть возможность перезагрузить сервер и загрузиться с LiveCD, можно воспользоваться простым средством — утилитой Gparted, которая позволяем менять размер разделов мышкой.
Запускаем утилиту — выбираем диск, с которым будем работать — кликаем правой кнопкой по разделу, который хотим увеличить и выбираем Resize/Move:
В открывшемся окне с помощью мышки или форм меняем размер раздела:
Нажимаем кнопку Resize/Move.
Проверяем изменения в окне программы и сохраняем настройки кнопкой «Apply All Operations»:
Источник
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).
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.
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.
To reduce to 5G
To reduce by 5G
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.
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.
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.
Источник