I know how to create a swap file and use it as swap. But I have to configure the size of the file beforehand and the space is used on the disk, if the swap is used or not.
How do I create a swap that has an initial size of 0 and grows on demand?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
Swapspace is old and unmaintained and could lead, one day, to problems in modern systems. I think that the best solution for dynamic swap is to:
sudo apt install dphys-swapfile sudo update-rc.d dphys-swapfile enable
/etc/dphys-swapfile and finally
sudo service dphys-swapfile start
SwapSpace is a utility that creates a ‘dynamic swap file’ which according to the requirements of the operating system changes its size.
So you can even forget about creating a virtual swap file and just install “SwapSpace” and it’ll automatically create one for you and will even resize it when necessary.
You can also use ‘Swapspace’ side by side with a manually created swap file and when the manually one gets filled ‘Swapspace’ will automatically create another one for the OS so the OS will always have a swap space and it enhances the stability.
Another useful thing about “SwapSpace” is that, whenever it can, it’ll reduce the size of the SwapSpace and “release” those bytes into user file system and according to the developers this reduction helps to increase the swap file’s performance as well (plus your “precious” HDD space is not wasted too).
sudo apt-get install swapspace
And adjust the config file to your needs. I set the minimum to
0 on my VM debian machine with just 8GB HDD
Additionally I also set the swappiness to
0 to minimize the usage of the precious HDD space on my VM:
To change the system swappiness value, open
/etc/sysctl.conf as root. Then, change or add this line to the file:
vm.swappiness = 0
(Reboot for the change to take effect)
Afaik, any swap partition that you would make using fdisk for example, would need any space greater than 0, as you are modifying the space from an existing disk and reallocating it into somewhere else.
Anyway, and answering your question, you can easily make a small partition, assign it as swap under fdisk, and afterwards:
1) disable swapping with
2) resize partition with
3) format the partition with
4) re-enable the swap space with
Afterwards, you can use
cat /proc/swaps to check if it has been upgraded or not. You can easily use this on a script, depending on your system specs, and run it on demand for whenever you need to increase that swap space. Something like:
$ swapoff -v /dev/swapvol1 $ lvresize /dev/swapvol1 -L +1G $ mkswap /dev/swapvol1 $ swapon -v /dev/swapvol1