How to create a filesystem for a directory on Linux

How to create a filesystem for a directory on Linux
Photo by Lukas / Unsplash

Hey everyone!

Hope you are safe and doing great!

Sometimes we might want to separate some Linux system directories from the root filesystem and put a directory in its own filesystem.

In the short guide, we will move /opt directory in its own filesystem.

1. Check how much free space is allocated for the current volume group.

sudo vgs

2. Stop all active services within the directory which you want to move.

sudo lsof | grep /opt

3. List all logical volumes within the volume group.

sudo lvs

4. Create a new logical volume for the directory within the logic group.

sudo lvcreate -L 150G -n opt vgroot

5. Create a new filesystem for the logical volume.

sudo mkfs.xfs /dev/mapper/vgroot-opt

6. Mount a new logical volume to /mnt

sudo mount /dev/mapper/vgroot-opt /mnt

7. Use rsync to do the exact copy of /mnt directory.

sudo rsync -uav /opt/ /mnt

8. Check if the content /opt directory has been successfully copied to /mnt

sudo ls /mnt

9. Unmount /mnt directory.

sudo unmount /mnt

10. Remove everything in /opt directory.

sudo rm -rf /opt/*

11. Edit /etc/fstab and add a new logic volume to make it mounted every time when a server boots.

sudo nano /etc/fstab

11.1 Add this row to the file.

/dev/mapper/vgroot-opt	/opt	xfs	defaults	0	0

12. Mount all filesystems which mentioned in /etc/fstab

sudo mount -a

13. Check filesystems.

sudo df -h

14. Check directories

sudo ls /opt

15. Check how much free space allocated for the current volume group.

sudo vgs

16. (Optional) Reboot the server/instance and check if the services from the directory work well.

sudo shutdown -r

You are awesome!

That is it. Hope this short guide helped you and saved your time for the best.

Thank you for reading and see you soon.