How to add more memory to a Ubuntu Server with a Swap File


Types-of-Computer-MemoryIn linux Swapping is the process where memory is copied to the hard disk in space called swap space to free up physical memory. This is the same as virtual memory in linux. It is useful for two important reasons, First, when the system requires more memory than is physically available the kernel swaps out less used pages and gives memory to the current application (process) that needs the memory immediately. Second, a significant number of the pages used by an application during its startup phase may only be used for initialization and then never used again. The system can swap out those pages and free the memory for other applications or even for the disk cache.

There are two ways of setting up swap space in Linux, the most common is to set aside a swap partition when setting up the machine, the second is to set up a swap file. The later is useful if you didn’t set up a swap partition or if you’re using something like an Amazon EC2 micro instance that does not come pre-configured with a swap partition.




To set up a swap file you first need to allocate a file of the size you want available for the swap file, in the following command we’ll setup a new file called /mnt/swap with the size of 1024 MegaBytes,

sudo fallocate -l 1024m /mnt/swap

We now need to change the permissions:

sudo chmod 600 /mnt/swap

Next we need to format the file to be used by swap:

sudo mkswap /mnt/swap




and finally we need to tell the system to use file for swapping:

sudo swapon /mnt/swap

Thats all there is too it, once this has been completed your system will be using the swap file to swap memory, you can test this with the command:

free -m
             total       used       free     shared    buffers     cached
Mem:           590        558         31          0         10        152
-/+ buffers/cache:        394        195
Swap:          999         14        985

, , , , , , , , ,

Comments are closed.