硬碟快滿了就得擴容,不論是獨立主機還是雲端主機新買的雲硬碟,做法都類似。以下以阿里雲 VPS 為例,說明兩種掛載擴容路線。
先談兩個現實限制:其一,阿里雲預設不用 LVM,系統盤 /dev/xvda1 因此無法擴容,若有大量資料要存,一開始就該把擴容規劃進去,資料量越大後續操作的風險越高;其二,它無法在後台無縫擴容,必須登入主機手動調整,對非專業人士並不友善。
先確認現況:
[root@iZ94zz3wqciZ ~]# df Filesystem 1K-blocks Used Available Use% Mounted on /dev/xvda1 20641404 14778400 4814480 76% / [root@iZ94zz3wqciZ ~]# fdisk -l /dev/xvda1 * 1 2611 20970496 83 Linux // id 為 83,非 LVM Disk /dev/xvdb: 23.6 GB ... // 新買的硬碟
分區:
[root@iZ94zz3wqciZ ~]# fdisk -S 56 /dev/xvdb Command (m for help): n Command action e extended p primary partition (1-4) p Partition number (1-4): 1 Command (m for help): wq
格式化並建立掛載點:
[root@iZ94zz3wqciZ ~]# mkfs.ext4 /dev/xvdb1 [root@iZ94zz3wqciZ ~]# mkdir /mnt/fastdfs [root@iZ94zz3wqciZ ~]# echo "/dev/xvdb1 /mnt/fastdfs ext4 defaults 0 0" >> /etc/fstab [root@iZ94zz3wqciZ ~]# mount -a [root@iZ94zz3wqciZ ~]# df /dev/xvdb1 22694396 176064 21365516 1% /mnt/fastdfs
這樣就把一顆獨立硬碟接進系統了。操作簡單,但擴充性不足,不建議長期採用。
先還原測試環境,刪掉剛剛的分區:
[root@iZ94zz3wqciZ ~]# umount -a [root@iZ94zz3wqciZ ~]# fdisk /dev/xvdb Command (m for help): d Command (m for help): wq
確認並載入 device-mapper 模組(2.6.9 以後核心已內建,只需載入):
[root@iZ94zz3wqciZ ~]# yum install lvm2 device-mapper [root@iZ94zz3wqciZ ~]# lsmod | grep dm_mod dm_mod 84337 5 dm_mirror,dm_log
建立 LVM 分區的關鍵是把類型改成 8e:
Command (m for help): n p Partition number (1-4): 1 Command (m for help): t Hex code (type L to list codes): 8e Changed system type of partition 1 to 8e (Linux LVM) Command (m for help): wq
接著依序建立物理卷、卷組與邏輯卷:
[root@iZ94zz3wqciZ ~]# pvcreate /dev/xvdb1 [root@iZ94zz3wqciZ ~]# vgcreate myfiles /dev/xvdb1 [root@iZ94zz3wqciZ ~]# vgchange -ay myfiles [root@iZ94zz3wqciZ ~]# vgdisplay myfiles | grep "Total PE" Total PE 5629 [root@iZ94zz3wqciZ ~]# lvcreate -l 5629 -n fastdfs myfiles
格式化並掛載:
[root@iZ94zz3wqciZ ~]# mkfs.ext4 /dev/myfiles/fastdfs [root@iZ94zz3wqciZ ~]# echo '/dev/myfiles/fastdfs /mnt/fastdfs ext4 defaults 0 0' >> /etc/fstab [root@iZ94zz3wqciZ ~]# mount -a [root@iZ94zz3wqciZ ~]# df /dev/mapper/myfiles-fastdfs 22694396 176064 21365516 1% /mnt/fastdfs
這才是 LVM 的價值所在——線上擴充,不必重灌:
[root@iZ94zz3wqciZ ~]# fdisk /dev/xvdc # 分區並將類型設為 8e [root@iZ94zz3wqciZ ~]# reboot [root@iZ94zz3wqciZ ~]# pvcreate /dev/xvdc1 [root@iZ94zz3wqciZ ~]# vgextend myfiles /dev/xvdc1 [root@iZ94zz3wqciZ ~]# vgdisplay myfiles | grep "Total PE" Total PE 6907 [root@iZ94zz3wqciZ ~]# lvresize -l 6907 /dev/myfiles/fastdfs [root@iZ94zz3wqciZ ~]# resize2fs /dev/myfiles/fastdfs [root@iZ94zz3wqciZ ~]# df -h /dev/mapper/myfiles-fastdfs 27G 172M 26G 1% /mnt/fastdfs
如果未來會頻繁擴容,LVM 幾乎是唯一合理選擇。要提醒的是,任何涉及分區表與檔案系統的操作前都請先備份資料,並在 /etc/fstab 改動後跑一次 mount -a 驗證,避免開機失敗。