Creating and Enabling Swap Memory in Ubuntu 14 & 15

A Swap File in Linux is a designated storage in Linux Filesystem where data can be stored temporarily when it can no longer be contained in the RAM, this can help prevent your Sytem from crashing. Sometimes my 4G RAM gets filled up when I’m running heavy packages which hangs my system, but with Swap; some data can be moved to it temporarily till the RAM is freed up again.

Checking For Swap Existence
Before we continue in creating Swap, let’s check if there is Swap already existing in the sytem. Run this

$ free -m 

Should output something similar to the pic above showing the swap as 0

Swap:            0          0          0

Creating Swap
Now we’ve seen that, we are now going to create a Swap file out of our disk memory in this post I’m going to create a swap file of 2GB by typing:

$ sudo fallocate -l 2G /swapfile

That won’t return anything but the prompt, now check the swapfile created and see if it created the correct amount specified by typing:

$ ls -lh /swapfile
-rw-r--r-- 1 root root 2.0G May  7 14:13 /swapfile

Enabling Swap
We’ve created a swap file but the Operating System does not know if what you created is to be used as a Swap, in this part we are going to tell the OS to use the file as a Swap. Firstly we are to make the Swap only accesible by root; as Swap file store temporary data that cannot be contained in the RAM, this data are not to be exposed to ordinary user which can cause great harm. Locking down the swap file to admin only by typing

$ sudo chmod 600 /swapfile

Verify the correct permission set

$ ls -lh /swapfile
-rw------- 1 root root 2.0G May  7 14:26 /swapfile

Now we are preparing it to become a Swap file in typing:

$ sudo mkswap /swapfile


Setting up swapspace version 1, size = 2097148 KiB
no label, UUID=ad3663f1-dc22-4305-b064-954086fa4816

File is ready to be mounted as swap, lets do it!

$ sudo swapon /swapfile

Cool! Swap has been set successfully, you can verify by running free -m again and you get this:

 total used free shared buffers cached
Mem: 3835 2979 856 442 118 1155
-/+ buffers/cache: 1705 2130
Swap: 2047 0 2047


Automatically Mount Swap on Boot
Now we’ve created the swap, this swap is temporary and will unmount once we restart, but there is a way to keep it mounted on-boot; by setting it in fstab, edit this as root /etc/fstab and add the below code at the last line:

/swapfile none            swap    sw              0       0

Then save.

I hope this helps 🙂