How to add a swap file in linux

root's picture

Sometimes you need to increase the swap size and you are unable to modify the actual swap partition from various reasons. One of them would be that you don't have LVM. Well, in this situation the only solution is to add another swap. If you don't have free disks around, you can create a swap file and use it like normal swap. Here we go:

Make sure you have enough space:

[root@gzlinux ~]# df -h .
Filesystem            Size  Used Avail Use% Mounted on
/dev/sdb1              30G   22G  6.3G  78% /

Create the swap file (1024x1M = 1G):

[root@gzlinux ~]# dd if=/dev/zero of=/myswapfile bs=1M count=1024
1024+0 records in
1024+0 records out
[root@gzlinux ~]# ls -la /myswapfile
-rw-r--r--  1 root root 1073741824 Jan  8 07:20 /myswapfile

Create the swap area inside this image we have just created:

[root@gzlinux ~]# mkswap /myswapfile
Setting up swapspace version 1, size = 1073737 kB

Set up the permissions (for security's sake):

[root@gzlinux ~]# chown root:root /myswapfile
[root@gzlinux ~]# chmod 0600 /myswapfile

Activate the swap file:

[root@gzlinux ~]# swapon /myswapfile
[root@gzlinux ~]# swapon -s
Filename                                Type            Size    Used    Priority
/dev/sdb5                               partition       1052216 1051448 -1
/SWAP                                   file            1048568 1045596 -2
/myswapfile                             file            1048568 0       -4

Add the swap to /etc/fstab, to have it activated automatically on reboot. Use any editor you like or the command below:

If you are not familiar with redirection, please be careful: the double "greater-than" sign (>>) is to append the line at the end of file. Only one "greater-than" sign (>) would delete the entire content of the file and write the line after so please be careful!

echo "/myswapfile swap swap defaults 0 0" >> /etc/fstab

Thou shalt not steal!

If you want to use this information on your own website, please remember: by doing copy/paste entirely it is always stealing and you should be ashamed of yourself! Have at least the decency to create your own text and comments and run the commands on your own servers and provide your output, not what I did!

Or at least link back to this website.