Proxmox уменьшить размер диска виртуальной машины
Чаще всего «слабым звеном» в работе виртуальной машины Windows на Proxmox является дисковая подсистема. Ниже собран несколько советов, которые помогут приблизиться к максимально возможным скоростям.
Здесь собраны советы только по ускорению дисковой подсистемы программными методами. Использование SSD в single или raid — отдельная тема для обсуждения.
Рекомендуется использовать устройства virtio там, где это возможно. Это обеспечит лучшую производительность. К примеру, использование VirtIO Generic Disk Controller по сравнению с эмулируемым IDE -контроллером увеличит последовательную запись в 2 раза. Использование сетевого интерфейса VirtIO увеличит производительность сетевого интерфейса в 3 раза по сравнению с эмулируемой сетевой картой Intel E1000.
Practical Examples
2. Enlarge the partition(s) in the virtual disk
Depending on the installed guest there is several diffent ways to resize the partions
Example 1 – Increasing disk size
In this scenario, we have a virtual machine with the VMID 111 that has a c: drive partition set to 20 GB. We need to increase the size of the partition to 25 GB.
Click to enlarge
We shutdown the virtual machine and as described earlier, I’ll make a console connection (through putty) to the PVE host. I go to the folder holding all my virtual disks files (by default, all the virtual disks are located in /var/lib/vz/images) and then cd to the folder holding the virtual disk I want to resize. (In my case the vmid is 111 – view screenshot)
Click to enlarge
I need to increase the size of the disk up to 25 GB. I basically need to add 5 GB to the initial file. I’ll then type the following command
qemu-img resize vm-111-disk-1.raw +5GB
Click to enlarge
I can now reboot the virtual machine and you will see that the disk size has been set to 25 GB within the Operating system
Click to enlarge
16 thoughts on “ Proxmox VE – Resize your virtual Hard disks – Part I ”
sry, have you tested it. as i guessed it does not work as the booloader has not been updated with the new size. please delete this desaster of a howto
Yes It has been tested and validated multiple times…
I might have helped you if you could have provided a more detailed description of your problem and the steps you’ve performed….Again, this procedue has been tested so this should be working
Thank you! It’s work perfectly. How enlage disk in windows?
you can read the part II of the post. This will explains how to resize disks within Operating system. You’ve missed the link to part II…. so have a look at
It appears when browsing to /var/lib/vz/images, these are virtual drives on the hosts’ local storage, correct? If so, how would one go about resizing a drive in an LVM group on an iSCSI SAN?
Also, I’m running Proxmox 2, so I’m guessing there may be more to the web GUI now?
If you can wait a little bit…I’ll have to check first… This might become a new post….
Sounds good, thank you.
If it helps your next post, I was able to find that the drives on an iSCSI SAN are referenced under /dev/dm-0, dm-1, etc. You can run ‘dmsetup ls’ to see exactly which drives are behind the ‘dm-x’ symbolic links.
What I did was:
– Shut down the desired VM
– Add/create a second hard drive to it, the full desired size
– SSH into the Proxmox server and run a dd command, if=vm-101-disk-1 of=vm-101-disk2
– When that copy/duplication job is done, remove the smaller drive from the VM
– Start the VM and tell Windows to expand the volume to occupy the new additional free space
Let me know if you find a more elegant/streamlined way. 🙂
To answer your question (short version), yes there is an easier way to increase the size of the virtual machine….
– first, get info about LVM – typing lvdisplay
– locate the vg name that needs to be modified
– type lvresize -L+SizeGB
– type lvchange –refresh
– within the os, need to resize the disk or create additional partition….
A post is on its way…..
Hope this answer your question
FYI – I tried to shrink the Windows 7-64 virtual disk (virtio driver) by 10Gb. The VM did not boot up with new image file. I’ve got a restore interface with no dirve found.
Sorry to hear that, have you followed all the steps – more specifically Step 1 where I mention about the backup of your VM in case something goes wrong….
anyway, can you check one of the following
Have you typed the correct command
This is the correct command to shrink size of a disk qemu-img resize vm-101-disk-1.raw – – -1OG If you have typed qemu-img resize vm-101-disk-1.raw -10G, then the new size of the disk would be 10 GB. this is not a correct command. You might have deleted some files now
-> in your Proxmox Console, what’s the size of the disk ?
can you boot up your virtual machine and start in Recovery Mode and see if the wizard can restore/repair your Windows Installation ?
Possibly, still using recovery Mode (Press F8 during the boot Process), can you open a command prompt and see if you can list disk and partitions using Diskpart.
If recovery mode is not detecting disk, you will need to load the virtio drivers. Try to repair from this mode. If this fail, open a command prompt and check that you can see the disk and partitions using diskpart utility. check that the partition size and filesystem is showing up correctly.
Let me know what you can see and I’ll try to help out
I’ll check again the procedure but I’ve used many times with Windows 7/windows 2008 R2 64-bit and had really minimum issues with that
Hope this help
See ya
Yes, I have a backup and already restored the VM.
I followed your instructions closely and am sure that the command line was correct. The resultant size of .raw file was what I expected.
The Window restore/repair wizard was started automatically upon boot with the new image.
The C: drive was not found and I was prompted to insert disk with drivers as if virtio scsi driver was lost.
I did not experiment with further recovery options.
Do you think if the disk defragmentation might be needed prior to shrinking?
I am going to try drive shrinking again on the same file and will report results.
It looks like with drive shrinking two basic steps should be taken in reverse order. First, you shrink drive in Windows client. The shrink wizard queries disk for available shrink space up to the point where any unmovable files are found. (In my case the maximum shrink size was 7GB, not 10GB.)
Second, you shrink the drive on host using maximum shrinkage size determined by the client.
So, instead of my voluntaristic 10GB I shrank the volume by 7GB and everything went perfectly!
Thanks for very useful tutorials.
This is great news….(I’m Happy you have your virtual machine back online). You might be right in your statement.
It might be indeed good to warn the user that you have a max shrinking size.
I’ll probably update this post to be more specific about the shrinking part..thank to you
See ya around
Till Next Time
STOP BEFORE YOU LOOSE DATA.
Do not follow the steps in this tutorial for reducing the virtual hard drive size.
BEFORE you try reducing the size of a virtual hard drive (VHD) you MUST reduce the partition size first so that the empty space at the end of the VHD is at least the same or greater than the amount you are going to reduce the VHD by. Otherwise you will simply chop the end of the partition off thereby corrupting it and the underlying filesystem and loose any files that are stored in that chopped of section of the partition.
The steps for reducing a vhd should largely happen the reverse order and with the reverse effect of enlarging a vhd.
As a quck example at a minimum (not tested):
Step 1 – backup your VM!!
Step 2 – Reduce the size of the partition(s) on the VM. This is done within the VM itself using whatever appropriate tools are necessary such as windows disk management or a gparted boot disk etc. So if you are reducing the VHD from 25GB to 20GB, then reduce the partition so that it is now less than 20GB e.g. 19.8GB.
Step 3 – Turn off the VM
Step 4 – resize the vhd using the instructions provided in this tutorial (probably)
Step 5 – Optional – If you reduced the partition in step 2 to be less than the reduced VHD size, you might want to increase that partition to fill up the remaining space on the now resized vhd. Example, reduced the partition to 19.8GB, resized the vhd to 20GB, so now increase the partition to fill up the remaining 0.2GB.
Good luck and don’t forget to backup and then test the procedure.
thank you for the feedback. indeed, for the shrinking action, you need to first shrink the disk in the vm and then shrink the virtual disk file. We have updated the post slightly to reflect the differences in the process when increasing or shrinking the disk size. This was already mentioned in the comment section but we never had the time to update this post
Till next time
See ya
Настраиваем swap в Proxmox
Чтобы добиться максимального быстродействия дисковой подсистемы у сервера Proxmox стоит отключить swap или снизить процент его использования.
Часто на сервере Proxmox можно наблюдать картину:
Это все из-за того, что Debian по умолчанию при использовании более 40% ОЗУ , начинает пользоваться swap. Для рабочей станции с небольшим количеством ОЗУ – это нормально, но для сервера, где оперативной памяти в разы больше этот параметр не совсем подходит.
- отключить swap в Proxmox вообще;
- ограничить процент использования swap в Proxmox.
Online for Windows Guests
- Guest is Windows 7, Windows Vista or Windows Server 2008
- logon as administrator and extend the disk and filesystem (Using Disk manager)
- For more info www.petri.co.il/extend-disk-partition-vista-windows-server-2008.htm
- Guest is Windows 10: logon as administrator and extend the disk and filesystem (Using Disk manager). If you do not see the ability to extend the disk (i.e. nothing seems to have happened as a result of using the resize command), go to the Windows command prompt and do a: shutdown -s -t 0 (This is a "normal" shutdown, as opposed to the "fast" shutdown that's the default for Win 8 and onwards.) After a reboot, you'll now see the ability to expand the disk.
PVE Configuration
- Thin-provisioned backing storage (qcow2 disk, thin-lvm, zfs, . )
- Virtio-SCSI controller configured on guest.
- Guest scsi* disks with the discard option enabled
- See Qemu trim/discard and virtio scsi for configuration details.
Online for Linux guests with LVM
Enlarge the physical volume to occupy the whole available space in the partition:
Enlarge the logical volume and the filesystem (the file system can be mounted, works with ext4 and xfs)
Lately, as you might have noticed, I’m focusing on KVM Virtual machines running Windows operating systems (the recent versions). This post will again focus on KVM virtual machines. We will talk about resizing virtual disks.
It might happen that your virtual machine is running out of space or that you have provisioned too much disk space and you want to change this. This operation can be performed within a Proxmox VE (PVE) infrastructure but only from the command line (the Web interface does not provide this option yet – maybe in version 2.0)
The resizing process is basically a 2-step process and the order of these steps are different if you are increasing or shrinking the size of the disk.
To increase the size of the disk, you will perform the actions in the following order
- increase the size of the virtual disk (through the command line)
- Then, you will increase the size of the partition within the Operating system in order to reflect the changes in disk size.
To Shrink the size of the disk, you will perform the actions in the following order
- first,you will shrink the size of the partition within the Operating system in order to reflect the changes in disk size.
- and then you will reduce the size of the virtual disk (through the command line)
Leave a Reply
Copyrights & Disclaimers
This blog and its content are freely available to users but copyrights applies. The content is copyright of c-nergy.be. This means that you cannot duplicate or (. )
Linux Guest Configuration
Modern Linux guest systems can use the well known fstrim command to trim a device and free all unused storage on the underlying device:
Many modern Linux distributions have already setup a timer or cron job which executes a TRIM about once a week.
Ограничиваем работу swap
Узнаем при каком проценте занятости ОЗУ , наш Proxmox начинает скидывать в swap:
Это стандартное значение. При такой настройке от 40% занятой ОЗУ , начинается заполнение свопа.
Для сервера нужно установить это значение близким к нулю. При нуле область подкачки использоваться вообще не будет. Можно установить это значение в 10, что позволит Proxmox’у использовать до 90% оперативной памяти без задействования механизма своппинга. При загрузке ОЗУ более 90% часть данных будет переносится в swap. Можно поставить это значение и в 5 и в 1.
Чтобы установить это значение, выполняем команду:
Если запустить эту команду без -w , то команда примениться до первой перезагрузки. Удобно для тестов.
Если знаете еще способы увеличения скорости дисковой подсистемы, то прошу оставлять их в комментариях.
Over time a guest's *.qcow2 disk files can grow larger than the actual data stored within them, this happens because the Guest OS normally only marks a deleted File as zero, it doesn't gets actually deleted (performance reasons), so the underlying qcow2 file cannot differentiate between allocated and used and allocated but not used storage.
In order to shrink the *.qcow2 files you've two options, enable TRIM support or zero out all free space of the partitions contained within the guest and then reconvert the image with qemu-img.
IMPORTANT WARNING: Always have offsite backups ready, you never know!
Offline for all guests
Use gparted or similar tool (recommended)
In gparted and possibly most other tools, LVM and Windows dynamic disc is not supported
Boot the virtual machine with gparted or similar tool, enlarge the partion and optionally the file system. With som linux clients you often need to enlarge the extended partion, move the swappartion, shrink the extended partion and enlarge the root partion. (or simple delete the swap and partion andre create it again - but remember to activwate the swap agin (last step).
Gparted have some warnings about some specific operations not well supported with windows guest - outside the scope of this document but read the warnings in gparted.
Resizing the Virtual Disk file- How To
Let have a look to the first part of the process.
Step 1 – Backup your Virtual Machine
Before performing this operation, you should first backup your virtual machine in case something goes bad – shouldn’t but you never know 🙂
Step 2 – Power off your Virtual Machine
You should power off your virtual machine before applying changes. This ensures that the modifications are committed correctly by the PVE infrastructure.
Step 3 – Resizing the virtual disk
As mentioned earlier, to perform this change, you need to go through the command line (no GUI available yet). You will need to connect to the PVE Console locally or remotely via putty for example. From the console, if you type the following command
qemu-img –help
Click to enlarge
You will see a list of supported options. If you have a recent Proxmox VE installation, you will see an option called resize. As the name implies, using this option will allow you to increase or shrink the size of the virtual disk in qcow2,raw or vmdk format. (that’s cool all supported format used by PVE). The command can be used as follow
Note : Wait before using this command – read this till end !!
Step 4 – Checking news the virtual disk size
You can use the ls –lh command to check that the file has been modified accordingly.
Click to enlarge
Or you can use the qemu-img info to check that the file has been resized as required.
Click to enlarge
All in all the process is really not too difficult and you should be able to resizing disks image file as needed. Before closing this post, I thought that having practical examples might be useful.
Windows Guest Configuration
For those Windows versions which support TRIM (Win7/2008R2 and up should be supported, see this) you should not have to setup anything, Windows should periodically trigger a TRIM to the disks.
You can see if TRIM is enabled with:
This should output 0 (zero) else set it with:
This solution is no longer necessary and is only needed on Windows XP and earlier and older Linux distributions that don't support fstrim.
When you resize the disk of a VM, to avoid confusion and disasters think the process like adding or removing a disk platter.
If you enlarge the hard disk, once you have added the disk plate, your partition table and file system knows nothing about the new size, so you have to act inside the VM to fix it.
If you reduce (shrink) the hard disk, of course removing the last disk plate will probably destroy your file system and remove the data in it! So in this case it is paramount to act in the VM in advance, reducing the file system and the partition size. SystemRescueCD comes very handy for it, just add its iso as cdrom of your VM and set boot priority to CD-ROM.
Shrinking disks is not supported by the PVE API and has to be done manually.
Another page (deleted) with overlapping content was Resizing disks | Archive
qm command
You can resize your disks online or offline with command line:
exemple: to add 5G to your virtio0 disk on vmid100:
For virtio disks:
Linux should see the new size online without reboot with kernel >= 3.6
Windows should see the new size online without reboot with last virtio drivers.
for virtio-iscsi disk:
Linux should see the new size online without reboot with kernel >= 3.7
Windows should see the new size online without reboot with last virtio drivers.
Создание жесткого диска
При создании Hard Disk у виртуальной машины, выбираем SCSI (последний пункт), в не VirtIO Block. VirtIO blk — это предыдущий «этап» развития. Если сервер подключен к надежному источнику бесперебойного питания, то тип кэша ставим в — write back. Если ИБП нет, то покупаем ИБП и ставим Write Back.
Если образы виртуальных машин размещены на SSD , то обязательно ставим галки Discard и SSD emulation, чтобы правильно работала технология TRIM . Эмуляция SSD не поддерживается на дисках VirtIO Block.
Включаем IO thread. Опция IO Thread работает только если в качестве контроллера установлено значение VirtIO SCSI или VirtIO SCSI single. Если этот параметр включен, Proxmox будет создавать один поток ввода-вывода для каждого контроллера хранения, а не один поток для всех операций ввода-вывода. Это позволяет повысить производительность. Особенно виден прирост скорости при использовании нескольких дисков.
Отключение swap в Proxmox
Отключить swap достаточно просто. Узнаем название раздела swap:
В нашем примере это /dev/nvme0n1p3.
Далее отключаем swap:
Эта команда временно отключит swap. Чтобы отключить его навсегда, нужно в /etc/fstab закомментировать строку с его монтированием:
Final Notes
So far, we have just changed the size of the virtual disk. Proxmox VE knows now that disk size has been updated. However, we might still need to perform additional actions within the Operating system to apply these changes. This will be explained in the next part of this post
Support Us
You can support us by downloading Brave Browser and tip us through Brave Browser Reward System.
Download FREE Brave Browser
You can also decide to Buy us a coffee if your think that the information provided here was useful to you.
This website and its content is copyright of c-nergy.be – © c-nergy.be – 2008 – 2021 – All rights reserved.
Не знаю чё там с проксмоксами, но Ceph замечательно себе поддерживает ресайз RBD.
Другое дело, что ты будешь делать с тем, что внутри RBD.
вот в этом и нюанс.
Ну, ты всегда можешь заюзать libguestfs или хотя бы livecd какой-нить.
И если хочешь ресайзить туда-сюда, бери что-то подходящее, типа ext4.
при lvm внутри все увеличивается онлайн. Уменьшить - задача нетривиальная, но пара ребутов машинки и она тоже решаема(не все фс умеют уменьшаться)
KVM же не умеет в ресайз дисков без стоп-старта вм.
то что внутри виртуалки не проблема. т.е. проксмокс нормально воспримет увеличение rbd ?
Непонятно к чему это относится. Выглядит как фичи ceph. Найти команду для pveceph я не смог.
Т.е. я просто средствами ceph могу сделать ресайз и проксмокс не будет ругаться ? Нужно ли останавливать вм при ресайзе rbd ?
Сложно сказать. Пробовал ceph с rbd привязать к KVM, насколько я понял так все упиралось в работу самого KVM с динамическими дисками. На тестовом стенде попробовать, по идее KVM(и Proxmox) ругаться будет, но это сугубо размышления. Удача любит смелых) Создать пробный пул с тестовой ВМ и смотреть
В гуи прямо кнопка есть - resize disk. С ceph прекрасно работает. Все происходит в онлайне, vm перегружать не нужно.
Можно увеличить. Но сама vm должна перечить виртуальный диск, чтобы увидеть новую емкость. В зависимости от ОС это можно сделать без ребута, а зачастую без ребута не обойтись.
3. Enlarge the filesystem(s) in the partitions on the virtual disk
If you did not resize the filesystem in step 2
Дисковый контроллер
В качестве SCSI Controller выбираем VirtIO SCSI . Далее качаем ISO -образ vitio-win.iso с последними драйверами, добавляем CD/DVD драйвер для машины. Монтируем скаченный образ. Загружаем ОС и устанавливаем необходимые драйвера. После всех манипуляций должно получиться вот так:
Online for Linux Guests
Here we will enlarge a LVM PV partition, but the procedure is the same for every kind of partitions. Note that the partition you want to enlarge should be at the end of the disk. If you want to enlarge a partition which is anywhere on the disk, use the offline method.
- Check that the kernel has detected the change of the hard drive size
(here we use VirtIO so the hard drive is named vda)
- Resize the partition 3 (LVM PV) to occupy the whole remaining space of the hard drive)
- Check the new partition table
Contents
The recommended version is to pass TRIM commands (known from SSDs) from the VM to the backing storage. This has the advantage that it works automatically, does not need to write the whole free parts of all disks to zero and must only be setup once.
Формат образа жесткого диска
Используем образы машин только в формате raw. Есть мнение, что qcow2 только немного уступает в скорости raw, но нам важна максимальная скорость. Из минусов использования RAW — нет снапшотов для резервного копирования. Если это критично, то выбираем qcow2. Нужна скорость — выбираем RAW .
Example 2 – Shrinking disk size
In this scenario, we have a virtual machine with the VMID 111 that has a c: drive partition set to 25 GB. We need to decrease the size of the partition to 20 GB.
Click to enlarge
Note :
You will first need to shrink the size of the disk in the Operating system first. To see how you can shrink the disk within the Operating System, check out the part II
I’ll shutdown the virtual machine, make a putty connection to the PVE host and go to the directory holding the virtual disk file I need to resize. To shrink a disk, you need to type the following command
qemu-img resize – – -5GB
Click to enlarge
If you boot your virtual machine, you will see that the disk has been reduced accordingly.
Note :
There is a difference in the notation between increasing and shrinking disk. If you type this command,
the new virtual disk will be only 5 GB in size. Pay attention when using the command to reduce the size. This is not what you want. Instead you need to type
qemu-img resize – – – 5GB
to shrink the size of the disk by 5 GB.
Читайте также: