跳转至

KVM 虚拟机硬盘扩容

操作环境

项目 说明
宿主机系统 支持 QEMU/KVM 的 Linux
虚拟机系统 Ubuntu 24.04 Server
磁盘格式 QCOW2
扩容前容量 80GB
扩容后容量 500GB

扩容前检查

1. 查看虚拟机磁盘信息

在宿主机上执行:

Bash
qemu-img info ubuntu24-server-1.qcow2

输出示例:

Bash
1
2
3
4
image: ubuntu24-server-1.qcow2
file format: qcow2
virtual size: 500 GiB (536870912000 bytes)
disk size: 9.94 GiB

2. 查看虚拟机内分区情况

在虚拟机内执行:

Bash
lsblk
df -h

确认当前磁盘使用情况和分区结构。

扩容步骤

步骤一:宿主机扩容磁盘

如果尚未扩容,先执行:

Bash
qemu-img resize ubuntu24-server-1.qcow2 500G

Note

扩容前建议对虚拟机做快照备份,防止操作失误。

步骤二:虚拟机内安装扩容工具

Bash
apt update
apt install -y cloud-guest-utils

Tip

如果 apt update 卡住,可能是网络源问题。可更换为阿里云源:

Bash
1
2
3
4
5
6
7
8
cat > /etc/apt/sources.list.d/ubuntu.sources << 'EOF'
Types: deb
URIs: http://mirrors.aliyun.com/ubuntu/
Suites: noble noble-updates noble-backports noble-security
Components: main restricted universe multiverse
Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg
EOF
apt update

步骤三:扩展分区

Bash
growpart /dev/vda 2

输出示例:

Bash
CHANGED: partition=2 start=4096 old: size=167766016 end=167770111 new: size=1048571871 end=1048575966

Warning

如果 growpart 报错,可能需要手动用 fdisk 删除并重建分区(保留起始扇区)。

步骤四:扩展文件系统

确认文件系统类型:

Bash
df -T /

如果是 ext4:

Bash
resize2fs /dev/vda2

如果是 xfs:

Bash
xfs_growfs /

步骤五:验证扩容结果

Bash
df -h
lsblk

确认根分区容量已扩展到预期大小。

常见问题

问题一:growpart 命令不存在

Bash
# 安装 cloud-guest-utils 包
apt install -y cloud-guest-utils

问题二:分区表无法扩展

如果 growpart 失败,手动操作:

Bash
1
2
3
4
5
6
fdisk /dev/vda
# d → 删除分区(记录起始扇区)
# n → 新建分区(使用相同起始扇区)
# w → 写入并退出
# 重启虚拟机
# 执行 resize2fs

问题三:扩容后容量未生效

检查是否遗漏步骤:

  1. 确认 qemu-img resize 已执行
  2. 确认 growpart 成功扩展分区
  3. 确认 resize2fsxfs_growfs 已执行

回滚方案

如果扩容后出现问题,可从快照恢复:

Bash
1
2
3
4
5
# 如果有快照
qemu-img snapshot -apply snapshot_name ubuntu24-server-1.qcow2

# 或者从备份恢复
cp backup.qcow2 ubuntu24-server-1.qcow2

注意事项

  1. 操作前备份 - 扩容前对虚拟机做快照或备份磁盘文件
  2. 选择维护窗口 - 部分操作需要重启虚拟机
  3. 记录起始扇区 - 手动分区时必须使用相同起始扇区
  4. 验证数据完整性 - 扩容后检查关键数据是否完整

参考命令速查

操作 命令
查看磁盘信息 qemu-img info xxx.qcow2
扩容磁盘 qemu-img resize xxx.qcow2 500G
查看分区 lsblk / fdisk -l
安装工具 apt install -y cloud-guest-utils
扩展分区 growpart /dev/vda 2
扩展 ext4 resize2fs /dev/vda2
扩展 xfs xfs_growfs /