Increase memory (RAM) in Ubuntu - linux by using swap file

On Linux server, you mostly face low memory issue, mostly on AWS instance free tier. When you want to install any new thing they need more free memory. If your server has 1 GB Ram and your application is required more than 1 GB memory to run then swap memory is very useful to resolve the memory issue in Linux.

What is Swap File
Swap is a Virtual RAM which acts as a RAM but uses the secondary storage to save data. With swap, a small portion of the hard drive is set aside and used like RAM. The computer will attempt to keep as much information as possible in RAM until the RAM is full. At that point, the computer starts moving inactive blocks of memory that are paged to the hard disk, freeing up RAM for active processes. If one of the pages on the hard disk needs to be accessed again, it will be moved back into RAM, and a different inactive page in RAM will be moved onto the hard disk (swapped). The tradeoff is disks and SD cards are considerably slower than physical RAM, so when something needs to be swapped, there is a noticeable performance hit.

Memory Swap File Working

The swap file is a file in Hard disc that stores the RAM content on the time of swapping page. Virtual memory (Virtual RAM) size depends upon the swap file size. 

To create the swap file and allocate virtual RAM in Ubuntu uses the mkswap command. Step by step commands to create virtual RAM is given below:

free -m
mkdir -p /var/swapmemory
cd /var/swapmemory
#Here, 1M * 2000 ~= 2GB of swap memory
dd if=/dev/zero of=swapfile bs=1M count=2000
mkswap swapfile
swapon swapfile
chmod 600 swapfile
echo "/var/swapmemory/swapfile none swap sw 0 0" >> /etc/fstab
#cat /proc/meminfo
free -m

free -m is used to free the RAM by swapping the pages from RAM  into the swap file. Now enjoy the free RAM.

 

 

Keywords: