QCOW2 is a virtual disk image format used by Proxmox Virtual Environment (Proxmox VE), an open-source virtualization management platform. In Proxmox VE, QCOW2 is the default virtual disk image format for virtual machines (VMs).
- What is QCOW2?
- QCOW2 vs. raw disk?
- Create a QCOW2 disk
- Convert and import a disk
- Shrink a QCOW2 disk manually
- Enable TRIM support
- Subscribe to 4sysops newsletter!
- Последовательность действий
- Заключение
- Навигация по записям
- Import Qcow2 image to the Proxmox server.
- Create a VM without OS.
- Click on create VM.
- OS configuration.
- Leave system settings to default and click on Next.
- Configure CPU.
- Memory configuration.
- Choose your network and click on next.
- Import the qcow2 image to the virtual machine in Proxmox.
- Attach the newly added virtual hard disk to the VM.
- Change the Boot Order.
- Boot the VM from the Imported QCOW2 image.
- Conclusion
- Процесс миграции
- Resume
- How to upload qcow2 image into Proxmox?
- Import the qcow2 image into the VM
- Add the newly imported disk to the VM
- PREVENT YOUR SERVER FROM CRASHING!
What is QCOW2?
QCOW2 stands for QEMU Copy-On-Write version 2, which is essentially a file format for disk images used by Quick Emulator (QEMU). Q EMU is open-source virtualization software commonly used with a kernel-based virtual machine (KVM). In Proxmox, both KVM and QEMU work together as a complete virtualization platform.
Below are a few characteristics of the QCOW disk image format:
QCOW2 vs. raw disk?
In a nutshell, both the QCOW2 and raw disk formats have pros and cons. You can choose QCOW2 if you need more features, but if I/O performance is your main priority, choose a raw disk format. If you have to choose a raw disk format, remember to use a Proxmox storage type that supports snapshots.
Create a QCOW2 disk
In Proxmox, when a new VM is created in file-based storage, the QCOW2 disk format is automatically selected. See the screenshot below for reference:
Proxmox uses the QCOW2 disk format by default when using file based storage
Thus, unless you manually change the disk format when creating a new VM or adding a new disk to an existing VM, the disk format is QCOW2, by default, provided that you are storing it in file-based storage. The next section explains how to convert a virtual disk to QCOW2.
Convert and import a disk
When you use a tool like the VMware vCenter Converter to migrate your VMs, you get virtual disks in the vmdk or raw format. In addition, there are many virtual appliances available in vmdk or raw format. So, whenever you want to import such disks into Proxmox, you can use the qm disk import command, as shown below:
# create a new VM without a virtual disk
qm create 108 —name metasploitable —memory 2048 —sockets 1 —cores 2 —net0 virtio,bridge=vmbr0
# import a vmdk disk as qcow2 format in proxmox
qm disk import 108 /mnt/metasploitable.vmdk local —format qcow2
# attach the qcow2 disk and configure the boot order
qm set 108 —scsi0 local:108/vm-108-disk-0.qcow2,discard=on —boot order=’scsi0;net0′
# start the new VM
qm start 108

Import and convert a virtual disk to QCOW2 using the Proxmox command line
The main command to note here is the qm disk import 108 /mnt/metasploitable.vmdk local —format qcow2, which converts and imports a vmdk disk in the QCOW2 format from the /mnt directory to VM ID 108. Similarly, you can use the qemu-img convert command to convert a disk from one format to another, as shown in the command below:
qemu-img convert -f raw /mnt/usb/windows-10.vmdk -O qcow2 /var/lib/vz/images/109/vm-109-disk-0.qcow2
The -f option specifies the source disk format, and the -O option specifies the output disk format. The above command converts a raw disk located in /mnt/usb directory to the QCOW2 format in the /var/lib/vz/images/109 directory on the Proxmox server. You can then create a new VM in Proxmox by attaching the new QCOW2 disk.
If you have a virtual appliance in Open Virtualization Appliance (OVA) format, you first need to extract it using the tar command, since OVA is essentially an archive containing an Open Virtualization Format (OVF) file and some other files. You can then import the OVF file with the help of the qm importovf command, as shown below:

Import a virtual appliance packaged as OVF in Proxmox
Again, remember that the —format qcow2 option is important, or the disk will be imported as raw. If you have a VM in Proxmox that you want to move to a different storage, check out this post.
Shrink a QCOW2 disk manually
Before doing anything, shut down the original VM, and make sure you have a good backup of the virtual disk file. To locate the virtual disk file, you can use the Proxmox VE Storage Manager (pvesm) command line tool, as shown below:
# view the Proxmox storage status
pvesm status
# list storage
pvesm list local
# locate the path of a virtual disk file
pvesm path local:107/vm-107-disk-3.qcow2
# duplicate the original virtual disk file
cp /var/lib/vz/images/107/vm-107-disk-3.qcow2 /var/lib/vz/images/107/vm-107-disk-3.qcow2.bak

Locate and back up a QCOW2 disk on the Proxmox server
You can see that the current file size is 24 GB. Once you have the backup file, you can move the original QCOW2 disk to another storage.
mv vm-107-disk-3.qcow2 ~/orig
To shrink the QCOW2 file, you can use the qemu-img convert command, as shown below:
# shrink the virtual disk file without compression
qemu-img convert -O qcow2 vm-107-disk-3.qcow2.bak vm-107-disk-3.qcow2
# shrink the virtual disk file with compression
qemu-img convert -O qcow2 -c vm-107-disk-3.qcow2.bak vm-107-disk-3.qcow2

Shrink a QCOW2 disk with compression on the Proxmox server
The first command shrinks a QCOW2 file without compression, and the second command shrinks it with compression. Compression takes longer but results in a much smaller file.

Viewing the QCOW2 file size after shrinking
To obtain more information about the virtual disk, use the qemu-img info command, as shown below:
qemu-img info vm-107-disk-3.qcow2

View the detailed information about the virtual disk
You can see that the virtual disk size is 64 GiB, whereas the actual QCOW2 file size is 18.5 GiB. When compression is done, start your VM. If everything works as expected, you can delete the backup files to reclaim the free space.
Enable TRIM support

Enable the discard option on a VM disk in Proxmox
fsutil behavior query disabledeletenotify

Check whether trim support is enabled on Windows
fsutil behavior set disabledeletenotify 0
Similarly, the same thing on Linux can be accomplished with the fstrim -av command. The systemctl status fstrim.timer command shows the status of the fstrim service and the configured discard timer on a Linux system.

Checking the fstrim timer on Linux
Configuring trim support is a one-time thing. Once it is configured correctly, you no longer need to worry about manually shrinking and optimizing the virtual disks. Everything will be taken care of automatically for you.
Subscribe to 4sysops newsletter!
That was all for this post. You just learned about the QCOW2 disk image format and how to convert/import a virtual disk from various formats to the Proxmox server.

Система виртуализации на базе Proxmox все больше набирает популярность при создании IT инфраструктуры в последнее время. Данное решение объединяет в себе черты профессиональной системы виртуализации с возможностью создания кластеров и централизованного управления с одной стороны. А также все свойства Open Source продукта с другой стороны. При миграции на данную систему управления виртуализации Вам скорее всего придется столкнуться с задачами импортирования виртуальных машин как из среды VMware, так и работающих под управлением гипервизора kvm. Как это сделать легко и просто со вторым типом виртуальных машин, используемых в open source среде хочется рассказать поподробнее.
Последовательность действий
Для начала миграции kvm виртуальной машины ее необходимо выключить на хосте источнике. После этого найти образ жесткого диска, который используется в виртуальной машине. Данный образ копируется на хост назначения с Proxmox, на котором мы будем проводить импорт. Допустим, образ нашего диска называется kvm_virtual_disk.qcow2.
Теперь создадим виртуальную машину в гипервизоре Proxmox с помощью утилиты qm. Данная программа одна из нескольких, часто используемых для управления и настройки Proxmox VE. В данном примере идентификатор машины будет 222, в реальной жизни используем любой свободный в нашей среде виртуализации. Также рекомендую использовать на всех виртуальных машинах qemu agent, для обеспечения более полного взаимодействия между гипервизором и виртуальной машиной. Для этого при создании ВМ добавляем опцию —agent enabled=1. Пример команды qm, создающий виртуальную машину, представлен ниже.
qm create 222 —bootdisk scsi0 —net0 virtio,bridge=vmbr0 —agent enabled=1
После этого проведем непосредственно импорт .qcow2 диска в гипервизор. Для этого также воспользуемся возможностями утилиты qm с параметром importdisk. Образец команды приведен ниже. В качестве датастора для хранения импортируемого диска мы в данном примере указываем local-lvm, в реальной жизни он может быть совершенно другим. Подразумевается, что образ диска .qcow2 находится в директории, из которой происходит выполнение команды.
qm importdisk 222 kvm_virtual_disk.qcow2 local-lvm
Когда операция успешно завершится, проводим заключительную операцию по привязке диска к виртуальной машине с помощью все той же утилиты qm. Это делается следующим образом.
qm set 222 —scsi0 local-lvm:vm-222-disk-0
После этого донастраиваем параметры CPU, Memory, если надо сетевых интерфейсов в веб панели Proxmox. Теперь наша виртуалка полностью импортирована и готова к работе в среде Proxmox. Осталось запустить ее и дождаться отклика в консоли.
Заключение
Небольшая статья показывает основные моменты для импорта виртуальных машин kvm в гипервизор Proxmox. Хотя, в гипервизоре есть удобный веб интерфейс для управления, однако, все основные действия в данном случае приходится делать с помощью утилит командной строки. С учетом того, как хорошо развивается проект Proxmox VE в целом, можно предположить, что в скором будущем данный функционал будет доступен и в веб интерфейсе.
Навигация по записям
I have been working with KVM for a long time now. I stuck to it because it is open-source and free for anyone to use it. I recently moved some of my KVM virtual machines to my newly built Proxmox server. As you may know, Proxmox is a virtualization hypervisor based on KVM itself, and it is free. And you need to pay only for the support if you want to.
If I ever need to copy/move a VM from one KVM server to another, I usually take the qcow2 image of the virtual machine out and create a new VM with that image, which is pretty easy.
Initially, when I tried to move the KVM VM to the Proxmox server, I thought it would be a cakewalk, and I could easily create a VM with the QCOW2 image within Proxmox. However, by default, there is no option to import a VM from a virtual hard disk in Proxmox, as we have in KVM. The default option is to use only an ISO image and boot from it. The challenge here is that I am from a networking background. If I want to spin up any virtual firewall or network appliances, most of them are not available in iso format. It is primarily available in virtual Hard disk formats such as QCOW2, OVA, VHD, etc.
To use KVM virtual hard disk (qcow2) as the VM hard disk in Proxmox, some changes need to be made on the Proxmox server to load the KVM VM successfully.
In this blog, we will install a Proxmox virtual machine using a qcow2 image. After the installation, you should be able to log in to the virtual machine and starts to use it. The steps I mentioned here are pretty easy.
Before you begin you need to have;
Import Qcow2 image to the Proxmox server.
You could import the qcow2 file to any directory. I will move the qcow2 image to the Proxmox server directory – /var/lib/vz/template/qemu
Using the SCP command from KVM, I have transferred the file.
If you don’t have direct SCP access, you could transfer the file using Filezilla or WinSCP softwares.
As you can see, the Ubuntu.qcow2 image is now available in the directory, with a size of 21GB.

Create a VM without OS.
Let’s go ahead and create a virtual machine in Proxmox without specifying the os.
Click on create VM.
In the general properties;
Node: Specify the node. VM ID: It will be auto-created. Name: Provide a meaningful name.

OS configuration.
In the OS configuration, by default, it would choose Use CD/DVD disk image file (iso)We are not specifying the OS now, hence choose Do not use any media.
Based on what operating system you are going to install, you need to choose the type and the version.
Since I am installing Ubuntu which is based on Linux, I choose Linux and the version as 5.x

Leave system settings to default and click on Next.
Depending on your storage requirement, you may increase, decrease, or even remove the storage here. After adding the qcow2 image, you will have two virtual hard disks. The first one you are adding here, and the second one is the qcow2 image that we import.

Configure CPU.
Configure the CPU based on the operating system requirement.
I am providing 2 CPUs.

Memory configuration.
Finally, the required memory depends on your operating system. You may provide the recommended memory size and click on next.

Choose your network and click on next.
You will see the new virtual machine created with ID 107.

Import the qcow2 image to the virtual machine in Proxmox.
We will now import the qcow2 image as the virtual hard disk for Proxmox.
Login to the Proxmox CLI and switch to the qcow2 image directory we imported.
Issue the below command to import the qcow2 virtual hard disk to the newly created virtual machine.
qm importdisk 107 ubuntu.qcow2 local-lvm
Tip: You can use the tab key while entering the command. For example, after importing the disk, when I hit the tab, I could see all the VMIDs present in Proxmox.

This import virtual hard disk will take time depending on the size of the qcow2 image. For me to import 21 GB of qcow2 image, it took precisely 1 min and 3 seconds.
Attach the newly added virtual hard disk to the VM.
Login to the Proxmox server web GUI.
Select the virtual machine created in step2.
Click on Hardware
You will see the newly imported qcow2 image as Unused disk 0.
Double click on the Unused disk 0, or select the disk and click on Edit.

You will get a pop-up to add the new virtual hard disk.

You will see a new hard disk has been added with a volume of 20GB alongside the first virtual hard disk.

In my case, I defined 20GB storage in the KVM, the same has carried over to the Proxmox, which should be good.
Change the Boot Order.
For the Proxmox to start booting from the newly added qcow2 to storage, we need to define it in the boot order.

The new virtual hard disk should be the primary boot device, select the newly added virtual hard disk virtio1 and click on the hamburger icon to drag to the top and click on Ok.

Boot the VM from the Imported QCOW2 image.
You may go ahead and select the virtual machine and click on Console and start the VM.
We have successfully booted into the Ubuntu machine, which we imported from the KVM using the qcow2 image.

Conclusion

Популярность системы виртуализации Proxmox-VE растет с каждым днем во многом благодаря ее разносторонним возможностям. Иногда возникает необходимость в перемещении ряда гостевых машин из одной среды виртуализации в другую. Как переместить KVM виртуальную машину с диском формата qcow2 я показывал ранее в статье — Импорт kvm виртуалок в Proxmox. Теперь хотелось бы рассказать как осуществить аналогичный процесс из среды vSphere. Не часто, но такая необходимость может возникнуть у любого системного администратора. Сама миграция в целом технически не сложная, однако требует знания определенных нюансов, для получения нужного результата. Как учесть эти тонкости и по шагам провести процесс транзита виртуальных машин из VMware в Proxmox показано далее в статье.
Процесс миграции
Из имеющихся возможных вариантов проведения перевода виртуальной машины из среды vSphere в среду Proxmox покажу простейший и как мне кажется наиболее прямолинейный способ.
Во-вторых, загружаем все файлы, полученные в результате предыдущей операции, на сервер Proxmox. Это можно сделать с помощью команды scp в Linux/MacOS или pscp в Windows.
В-третьих, когда все файлы будут загружены, можно начать импорт этих файлов в Proxmox-VE. Пример команды в CLI для импорта ВМ приведен ниже.
# qm importovf 101 /install/andreyus-test-vm.ovf local-lvm
Так 101 — это номер создаваемой виртуалки в Proxmox, a local-lvm — датастор, на котором будут находиться файлы данной ВМ. После того, как импорт будет полностью завершен, рекомендую выполнить следующие действия со вновь созданной виртуалкой:
В-четвертых, пришло время запускать импортированную нами виртуальную машину. Так как в средах vSphere и Proxmox наименование сетевых адаптеров различается, необходимо через VNC консоль гипервизора произвести их переконфигурацию. После этого должна появиться связь с виртуальной машиной из сети. Соответсвенно можно будет заходить на нее удаленно и выполнять дальнешие действия через SSH или RDP. В ряде случаев для нормального функционирования определенных сервисов потребуется перезагрузка гостевой машины.
В-пятых, нам необходимо отключить vmware-tools, и включить qemu agent. Так, например, в случае с использованием Ubuntu Linux в качестве гостевой ОС, нам нужно выполнить две команды в шелле виртуальной машины.
# sudo apt remove open-vm-tools
# sudo apt install qemu-guest-agent
Sixth, after the import procedure, all disks of the guest machine in Proxmox will take up full space on the datastore, regardless of the use of the Thin Provisioning functionality. If we use this technology, then it is necessary to execute the following command in the shell of the guest machine in order to free up unused space on the datastore.
Seventh, after all the necessary migration steps have been completed, I recommend removing the entire original VM from the vSphere environment. In addition, we delete all unnecessary files that were created or copied during the migration process. On this, the migration operation can be considered successfully completed and fully completed.
Resume
The algorithm described in this article is not complicated in itself and allows, if necessary, to smoothly transfer the required number of guest machines from the VMware environment to the Proxmox-VE environment. However, one must understand that most of the tasks require manual execution and take some time. Otherwise, the migration process should not cause difficulties for the readers of my blog.
Let us learn how to do Proxmox upload qcow2 with the support of our Proxmox support services at Bobcares.
How to upload qcow2 image into Proxmox?
Consider that after migrating from a standard Ubuntu installation to Proxmox for my home lab, we had one highly customized Ubuntu server that we wanted to integrate into Proxmox.
The final confibvguration in this case is as shown below:
VM shell final configuration
Import the qcow2 image into the VM
sudo qm importdisk VM ID qcow2 image storage name
The VM ID in this example is 102, the qcow2 image is /home/tom/Ubuntu.qcow2, and the storage name is Storage:
Add the newly imported disk to the VM
After that, the qcow2 image has been imported, added to the VM, enabled, and set to be the first in the boot order.
The VM configuration is finished, and the VM may now be booted and utilized as needed.
To sum up we have now seen how to do the Proxmox upload qcow2 with the support of our tech support team.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

