Friday, August 2, 2013

HOWTO Add a Swap File in GNU/Debian based Linux Systems

If you need additional swap space to improve the system performance or when find yourself in a situation where you can't add a new partition to your system or you can't extend your current swap, this can be a good choice to follow.

Note that with the 2.6 Linux kernel, swap files are just as fast as swap partitions. Even though I recommend using a swap partition. ;)

Step #1: Create Storage File

Login as the Root User, open a terminal window and follow the instructions below.

NOTE: You need to use the dd command to create swap file.

Type the following command to create 512MB swap file (1024 * 512MB = 524288 block size):
ximena@anneke:~$ dd if=/dev/zero of=/swapfile bs=1024 count=524288

Where:
    if=/dev/zero : Read from /dev/zero file.
Note that /dev/zero is a special file in that provides as many null characters to build storage file called /swapfile
    of=/swapfile1 : Read from /dev/zero write stoage file to /swapfile.
    bs=1024 : Read and write 1024 bytes at a time.
    count=524288 : Copy only 523288 input blocks.

Step #2: Set Up a Linux Swap Area


Type the following command to set up a Linux swap area in the file we created in Step #1:
ximena@anneke:~$ mkswap /swapfile

NOTE: The mkswap command is used to set up a Linux swap area on a device or in a file.



Setup correct file permission for security reasons, enter:
ximena@anneke:~$ chown root:root /swapfile
ximena@anneke:~$ chmod 0600 /swapfile


A world-readable swap file is a huge local vulnerability. The above command make sure only root user can read/write to the file. Finally, activate /swapfile1 swap space immediately, enter:
ximena@anneke:~$ swapon /swapfile


To activate /swapfile1 after Linux system reboot, add entry to /etc/fstab file. Append the following line:
/swapfile              swap   swap     defaults     0 0

Next time Linux comes up after reboot, it enables the new swap file for you automatically.

Step #3 Checking if the Swap is Activated

ximena@anneke:~$ free -m

You will be able to see the new swap area activated ;)