Linux extending file system

Extend a Linux file system after resizing a volume

The following topic walks you through the process of extending XFS and Ext4 file systems for Linux. For information about other file systems, see their documentation for instructions.

After you increase the size of an EBS volume, you must use file system–specific commands to extend the file system to the new, larger size. You can do this as soon as the volume enters the optimizing state.

To extend a file system on Linux, you need to:

Before you begin

  • Create a snapshot of the volume, in case you need to roll back your changes. For more information, see Create Amazon EBS snapshots.
  • Confirm that the volume modification succeeded and that it is in the optimizing or completed state. For more information, see Monitor the progress of volume modifications.
  • Ensure that the volume is attached to the instance and that it is formatted and mounted. For more information, see Format and mount an attached volume.
  • If you are using logical volumes on the Amazon EBS volume, you must use Logical Volume Manager (LVM) to extend the logical volume. For instructions about how to do this, see the Extend the logical volume section in the How do I create an LVM logical volume on an entire EBS volume? AWS Knowledge Center article.

Extend the file system of EBS volumes

Use the following procedure to extend the file system for a resized volume.

Note that device and partition naming differs for Xen instances and Nitro instances. To determine whether your instance is Xen-based or Nitro-based, use one of the methods:

[ec2-user ~]$ aws ec2 describe-instance-types --instance-type instance_type --query "InstanceTypes[].Hypervisor"
[ec2-user ~]$ TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \ && curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/system
To extend the file system of EBS volumes
  1. Connect to your instance.
  2. Resize the partition, if needed. To do so:
    1. Check whether the volume has a partition. Use the lsblk command. Nitro instance example In the following example output, the root volume ( nvme0n1 ) has two partitions ( nvme0n1p1 and nvme0n1p128 ), while the additional volume ( nvme1n1 ) has no partitions.
    [ec2-user ~]$ sudo lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT nvme1n1 259:0 0 30G 0 disk /data nvme0n1 259:1 0 16G 0 disk └─nvme0n1p1 259:2 0 8G 0 part / └─nvme0n1p128 259:3 0 1M 0 part 

    Xen instance example In the following example output, the root volume ( xvda ) has a partition ( xvda1 ), while the additional volume ( xvdf ) has no partition.

    [ec2-user ~]$ sudo lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT xvda 202:0 0 16G 0 disk └─xvda1 202:1 0 8G 0 part / xvdf 202:80 0 24G 0 disk 

    If the volume has a partition, continue the procedure from the following step (2b). If the volume has no partitions, skip steps 2b, 2c, and 2d, and continue the procedure from step 3.

    Troubleshooting tip

    If you do not see the volume in the command output, ensure that the volume is attached to the instance, and that it is formatted and mounted.

    Troubleshooting tip
    Important
    [ec2-user ~]$ sudo growpart /dev/nvme0n1 1
    Important
    [ec2-user ~]$ sudo growpart /dev/xvda 1
    Troubleshooting tips
    • mkdir: cannot create directory ‘/tmp/growpart.31171’: No space left on device FAILED: failed to make temp dir : Indicates that there is not enough free disk space on the volume for growpart to create the temporary directory it needs to perform the resize. Free up some disk space and then try again.
    • must supply partition-number : Indicates that you specified an incorrect partition. Use the lsblk command to confirm the partition name, and ensure that you enter a space between the device name and the partition number.
    • NOCHANGE: partition 1 is size 16773087. it cannot be grown : Indicates that the partition already extends the entire volume and can’t be extended. Confirm that the volume modification succeeded.
    [ec2-user ~]$ sudo lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT nvme1n1 259:0 0 30G 0 disk /data nvme0n1 259:1 0 16G 0 disk └─nvme0n1p1 259:2 0 16G 0 part / └─nvme0n1p128 259:3 0 1M 0 part 

    Xen instance example The following example output shows that both the volume ( xvda ) and the partition ( xvda1 ) are the same size ( 16 GB ).

    [ec2-user ~]$ sudo lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT xvda 202:0 0 16G 0 disk └─xvda1 202:1 0 16G 0 part / xvdf 202:80 0 24G 0 disk 
    [ec2-user ~]$ df -hT Filesystem Type Size Used Avail Use% Mounted on /dev/nvme0n1p1 xfs 8.0G 1.6G 6.5G 20% / /dev/nvme1n1 xfs 8.0G 33M 8.0G 1% /data . 

    Xen instance example The following example output shows that the /dev/xvda1 file system is 8 GB in size, its type is ext4 , and its mount point is / .

    [ec2-user ~]$ df -hT Filesystem Type Size Used Avail Use% Mounted on /dev/xvda1 ext4 8.0G 1.9G 6.2G 24% / /dev/xvdf1 xfs 24.0G 45M 8.0G 1% /data . 
    • [XFS file system] Use the xfs_growfs command and specify the mount point of the file system that you noted in the previous step. Nitro and Xen instance example For example, to extend a file system mounted on / , use the following command.
    [ec2-user ~]$ sudo xfs_growfs -d /
    Troubleshooting tips
    • xfs_growfs: /data is not a mounted XFS filesystem : Indicates that you specified the incorrect mount point, or the file system is not XFS. To verify the mount point and file system type, use the df -hT command.
    • data size unchanged, skipping : Indicates that the file system already extends the entire volume. If the volume has no partitions, confirm that the volume modification succeeded. If the volume has partitions, ensure that the partition was extended as described in step 2.
    [ec2-user ~]$ sudo resize2fs /dev/nvme0n1p1

    Xen instance example For example, to extend a file system mounted named /dev/xvda1 , use the following command.

    [ec2-user ~]$ sudo resize2fs /dev/xvda1
    Troubleshooting tips
    • resize2fs: Bad magic number in super-block while trying to open /dev/xvda1 : Indicates that the file system is not Ext4. To verify file the system type, use the df -hT command.
    • open: No such file or directory while opening /dev/xvdb1 : Indicates that you specified an incorrect partition. To verify the partition, use the df -hT command.
    • The filesystem is already 3932160 blocks long. Nothing to do! : Indicates that the file system already extends the entire volume. If the volume has no partitions, confirm that the volume modification succeeded. If the volume has partitions, ensure that the partition was extended, as described in step 2.

    Источник

    How to Extend XFS Filesystem in Linux Without LVM

    NOTE: I tested the concepts in this tutorial on a CentOS 8 system. However, the approaches discussed will work on any System using the XFS File system.

    Step 1: Show partition scheme information

    The first step is to get information about the available partitions. You can do this by using the lsblk command as:

    Step 2: Extend disk space

    The next space is to extend the disk space. You can do this by creating a new partition—or add a new drive.

    Confirm disk changes using the lsblk command as above.

    Step 3: Grow the partition

    The next step is to grow the partition. For this, we need to install the growpart package.

    Step 4: Extend & resize partition

    The next step is to use growpart to extend the partition. The command for that is:

    The command above will resize the third partition on /dev/sda as shown in the lsblk command.

    Finally, resize the root partition to fill the space using the resize2fs command. For example:

    Conclusion

    This tutorial covered the basic steps of extending the XFS filesystem without using LVM.

    About the author

    John Otieno

    My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

    Источник

    Расширение диска или раздела Linux

    Обновлено

    Обновлено: 04.04.2023 Опубликовано: 22.06.2017

    В зависимости от типа раздела и файловой системы, действия различаются.

    Любая работа с диском несет риск потери информации. Перед началом работ убедитесь в наличие резервных копий ценных данных.

    Шаг 1. Расширение раздела

    Мы рассмотрим варианты работы с обычными томами (разделами) и томами LVM. Проверить, какой тип раздела у нас используется можно командой:

    Нам интересны варианты part и lvm.

    Обычные тома (part)

    Допустим, есть диск /dev/sdb и раздел /dev/sdb2, который нужно увеличить. Разберем два подхода, сделать это.

    1. С помощью утилиты growpart (без отмонтирования раздела)

    Данная утилита позволяет увиличить размер слайса без необходимости его отмонтировать. Это очень удобно для работы с корневыми разделами. Данная утилита не установлена в системе. В зависимости от последней наши действия будут различаться.

    а) Для систем DEB:

    apt install cloud-guest-utils

    б) Для систем RPM:

    yum install cloud-utils-growpart

    Если наш диск имеет разметку GPT, то потребуется установить также утилиту gdisk.

    а) Для DEB:

    Установка growpart завершена. Идем дальше.

    Для расширения раздела /dev/sdb2 вводим команду:

    Мы должны увидеть что-то на подобие:

    CHANGED: partition=2 start=4096 old: size=20965376 end=20969472 new: size=41938910 end=41943006

    2. С помощью утилиты fdisk/parted (требуется отмонтировать раздел)

    Данный способ удобнее тем, что не нужно устанавливать дополнительных утилит, но он потребует отмонтирование раздела. Это можно сделать командой:

    В случае работы с корневой директорией, отмонтировать ее не получиться. В таком случае необходимо загрузить компьютер с Windows LiveCD или GParted Live.

    Подключаемся утилитой fdisk к /dev/sdb:

    Если мы работаем с разделом более чем 2Тб, используем утилиту parted.

    Удаляем раздел (не переживайте — все данные сохраняются):

    * в моем примере, раздел для удаления на второй позиции.

    На запрос начального и конечного секторов просто нажимаем Enter.

    Если раздел был загрузочный, добавляем соответствующий флаг:

    Еще раз проверяем, что получилось:

    LVM

    LVM-тома расширяются на лету, даже для корневых разделов. В данном примере, работаем с /dev/sda.

    Подробнее о работе с LVM читайте в инструкции Как работать с LVM.

    Открываем диск утилитой 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:

    * обратите внимание, что в данных примерах используются различные устройства.

    Если раздел был отмонтирован, монтируем его, например:

    Проверяем, что настройки применились:

    Увеличение разделов с Gparted

    Если работы выполняются на системе с графическим интерфейсом или есть возможность перезагрузить сервер и загрузиться с LiveCD, можно воспользоваться простым средством — утилитой Gparted, которая позволяем менять размер разделов мышкой.

    Запускаем утилиту — выбираем диск, с которым будем работать — кликаем правой кнопкой по разделу, который хотим увеличить и выбираем Resize/Move:

    Изменение раздела в GParted

    В открывшемся окне с помощью мышки или форм меняем размер раздела:

    Уменьшение или увеличение пространства в GParted

    Нажимаем кнопку Resize/Move.

    Проверяем изменения в окне программы и сохраняем настройки кнопкой «Apply All Operations»:

    Источник

    Читайте также:  Canon mf4730 драйвер linux
Оцените статью
Adblock
detector