Ubuntu: Using a swap file instead of swap partition for virtualized server VMs

ubuntuBefore virtualization, there was a stronger argument for using a swap partition instead of a swap file for servers.  A fragmented swap file could lead to performance issues that a statically sized and placed partition did not have consider.

But once virtualization comes into play, unless you go to great lengths to segment your storage pools, that swap partition is not guaranteed to be either statically sized or statically placed on a physical platter.  And at that point, you should consider using a swap file which provides more flexibility in sizing and capacity planning.

Here are instructions for adding a 16Gb swap file to Ubuntu:

validate current level of swap usage:

free -m

temporarily disable swap

swapoff -a

create a 16Gb swap file (1024 byte block * 16M = 16G)

dd if=/dev/zero of=/swapfile bs=1024 count=16M

apply proper ownership and permissions

chown root:root /swapfile

chmod 0600 /swapfile

Get the file ready as a swap file.  Note that the blockId output here has no meaning and cannot be used as the UUID in fstab or seen by the blkid command.

mkswap /swapfile

Add swap file to the persistent mounts referring to the path and not the UUID output by mkswap earlier.  Edit /etc/fstab and append the following line:

/swapfile none swap sw 0 0

re-enable swap

swapon /swapfile

validate new level of swap usage:

free -m

which should then display a 16Gb swap space

             total       used       free     shared    buffers     cached
Mem:         32045       8750      23295        706        213       4515
-/+ buffers/cache:       4021      28023
Swap:        16319          0      16319

And finally, in order to control the tendency of the system to use swap space, adjust the swapiness.  To discourage the use of swapiness, use a value like 10.

Check current level of swapiness

cat /proc/sys/vm/swappiness

To tune the level in /etc/sysctl.conf, append the following key

vm.swappiness=10

 

 

References:

https://www.linux.com/news/all-about-linux-swap-space

https://help.ubuntu.com/community/SwapFaq

https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04

https://www.howtoforge.com/ubuntu-swap-file

http://askubuntu.com/questions/390769/how-do-i-resize-partitions-using-command-line-without-using-a-gui-on-a-server

https://www.digitalocean.com/community/tutorials/how-to-configure-virtual-memory-swap-file-on-a-vps

http://askubuntu.com/questions/33697/how-do-i-add-a-swap-partition-after-system-installation