Skip to content

10. Disk & Storage

10.1 Viewing Disk Usage

bash
# df — view filesystem disk space
df -h            # Human-readable format
df -hT           # Include filesystem type

# du — view directory space usage
du -sh /home/user          # Total directory size
du -sh /home/*             # Size of each subdirectory
du -h --max-depth=1 /      # Size of directories under root

# ncdu — interactive disk analysis (requires installation)
ncdu /home
bash
$ df -hT
Filesystem     Type      Size  Used Avail Use% Mounted on
/dev/sda1      ext4       50G   22G   26G  46% /
tmpfs          tmpfs     2.0G     0  2.0G   0% /dev/shm
/dev/sda2      ext4      200G  156G   34G  83% /home
/dev/sdb1      ext4      500G  120G  355G  26% /data

$ du -sh /home/user/*
450M	/home/user/Documents
2.1G	/home/user/Downloads
850M	/home/user/projects
50M	/home/user/.cache

10.2 Disk Partitioning & Mounting

bash
# View disk and partition information
lsblk
sudo fdisk -l

# Mount a partition
sudo mount /dev/sdb1 /mnt/data

# Unmount
sudo umount /mnt/data

# View current mounts
mount | grep sdb

# Format a partition (dangerous operation! will erase data)
sudo mkfs.ext4 /dev/sdb1

# Set up auto-mount at boot (edit fstab)
sudo nano /etc/fstab
# Add a line: /dev/sdb1  /data  ext4  defaults  0  2
bash
$ lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0   250G  0 disk
├─sda1   8:1    0    50G  0 part /
└─sda2   8:2    0   200G  0 part /home
sdb      8:16   0   500G  0 disk
└─sdb1   8:17   0   500G  0 part /data
sr0     11:0    1  1024M  0 rom

10.3 LVM — Logical Volume Manager

LVM (Logical Volume Manager) allows you to flexibly resize partitions, unlike traditional partitions which are rigid.

bash
# The three steps to create LVM
# 1. Create Physical Volume (PV)
sudo pvcreate /dev/sdb /dev/sdc

# 2. Create Volume Group (VG)
sudo vgcreate data_vg /dev/sdb /dev/sdc

# 3. Create Logical Volume (LV)
sudo lvcreate -L 100G -n web_lv data_vg
sudo lvcreate -l 100%FREE -n backup_lv data_vg

# Format and mount
sudo mkfs.ext4 /dev/data_vg/web_lv
sudo mount /dev/data_vg/web_lv /var/www

# View status
sudo pvs
sudo vgs
sudo lvs

# Extend logical volume
sudo lvextend -L +50G /dev/data_vg/web_lv
sudo resize2fs /dev/data_vg/web_lv

10.4 Swap — Swap Space

bash
# View current swap
swapon --show
free -h

# Create a swap file (4GB)
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

# Make it persistent (add to fstab)
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Adjust swappiness (lower = less swap usage)
cat /proc/sys/vm/swappiness
sudo sysctl vm.swappiness=10
bash
$ free -h
              total        used        free      shared  buff/cache   available
Mem:          3.8Gi       2.7Gi       156Mi       128Mi       999Mi       820Mi
Swap:         4.0Gi       247Mi       3.8Gi

$ swapon --show
NAME      TYPE      SIZE  USED PRIO
/swapfile file        4G 247.8M   -2