How to create or add swap file on Linux and FreeBSD

Sometime you need to increase swap memory to run softwares that need more swap as the requirement or to improve the system performance. In this article I will show you on how to add swap file to get more swap memory on Linux and FreeBSD. We will create 1 GB or 1024 MB swap size.

1. Adding swap file on Linux

Login as root or change to super user then type the following command to create 1 GB swap file.

dd if=/dev/zero of=/swap1 bs=1M count=1024


For example, my result is as below:

bash-3.1# dd if=/dev/zero of=/swap1 bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB) copied, 28.3646 s, 37.9 MB/s

Run ‘mkswap’ to set up a Linux swap area on a device or in a file, in this case in the /swap1 file.

mkswap /swap1

For example:

bash-3.1# mkswap /swap1
Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=e501fc72-f731-4624-ab45-ee898f6cf1c5

After setting up the swap area, now we need to enable / activate the swap file by using ‘swapon’ command.

swapon /swap1

You are done. But the swap file will be disable if you reboot the system. To make it enable at boot, you need to add the swap file in the /etc/fstab file like below:

/swap1         swap             swap        defaults         0   0

2. Adding swap file on FreeBSD

Login as root or change to super user then run the following command to create 1 GB swap file. The same as in Linux but the swap file stored under directory /usr because this folder has more space in my system configuration.

dd if=/dev/zero of=/usr/swap1 bs=1M count=1024

For example, mine is as below:

root@freebsd# dd if=/dev/zero of=/usr/swap1 bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes transferred in 42.351062 secs (25353362 bytes/sec)

Then change the proper permission of the file:

chmod 600 /usr/swap1 

Enable the swap file in /etc/rc.conf to activate it at boot:

swapfile="/usr/swap1"

The last thing is enable or activate the swap file immediately by running the following command:

mdconfig -a -t vnode -f /usr/swap1 -u 0 && swapon /dev/md0

References:
1. http://www.cyberciti.biz/faq/linux-add-a-swap-file-howto
2. http://www.freebsd.org/doc/handbook/adding-swap-space.html