CentOS 7 create swap file on Xen or KVM

Sometimes when you are creating Xen or KVM machines in the cloud they don’t have any swap space by default.
If this is the case, you can easily add some space by performing the following steps.

Let’s create a file of 4GB to make 4GBs of swap space

fallocate -l 4G /swap.file

Make sure that only root can read and write to the file

chmod 600 /swap.file

Let’s format it as a swap file

mkswap /swap.file

You should get some output like the following

Setting up swapspace version 1, size = 4194300 KiB
no label, UUID=ac9254a2-021f-41f5-b099-ddc0ccf4a959

Now let’s make the swap available to the operating system

swapon /swap.file

and check its status

swapon -s

You should get output similar to this

Filename				Type		Size	Used	Priority
/swap.file                             	file	4194300	0	-1

Now make it permanent (reboot resistant) by appending the following to the bottom of your /etc/fstab

/swapfile   swap    swap    sw  0   0

So basically to create a 2GB swap file, cut and paste the following into your Xen/KVM VPS

fallocate -l 2G /swap.file
chmod 600 /swap.file
mkswap /swap.file
swapon /swap.file
echo "/swap.file swap swap sw 0 0" >> /etc/fstab

On some cloud systems fallocate (fast) does not work and you can substitute the following line

dd if=/dev/zero of=/swap count=2048 bs=1MiB

Author: Andrew

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.