Last Updated: February 25, 2016
· wajatimur

Creating Swap File on Ubuntu to Reduce Memory Usage

Check whether swap have been already turn on by using below command.

sudo swapon -s

If got an empty table that mean its not already turn on then we can proceed using below command to create an empty swap file. In example i create 1 Gb size swapfile.

sudo fallocate -l 1G /swapfile

We can confirmed the swap file were created by using below command, created file will give output of file with the size.

ls -lh /swapfile

Then we can enable the swap file by using below commands, changing mode to secure the swap file.

sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

To confirm the swap file have been successfully turn on by using back the following command. You will get a info on the swap available if everything is ok.

sudo swapon -s

We can make the swap enable permanently after next boot by adding below line to you /etc/fstab file.

/swapfile   none    swap    sw    0   0

To have immediate file write to swap, we can use below command.

sudo sysctl -w vm.drop_caches=3

You can notice the different of memory usage by using below command before and after.

free -m