adding extra swap file on ubuntu

Installed Ubuntu 15.04 on my low-key laptop and fire a build for llvm project. After a while ubuntu popped up internal error message. When I checked System Monitor- I ran out of RAM and Swap (4GB). So for sure I need more swap space on machine. Canonical as well as askubuntu.com have some good information on how to replace swap-files. Rather than replacing files- I am going to with adding another one. This time 16GB. Here are the steps, you will need superuser access- I prefer sudo to su.

First allocate 16GB memory and mount as 16gb.swap. Also ensure that this file can’t be read by anyone and fill it with zeros

1
2
3
4
5
6
7
8
9
sarangb@nuxbox:~$
sarangb@nuxbox:~$ sudo fallocate -l 16g /mnt/16gb.swap
sarangb@nuxbox:~$ sudo chmod 600 /mnt/16gb.swap 
sarangb@nuxbox:~$ sudo dd if=/dev/zero of=/mnt/16gb.swap bs=1024 count=16M
16777216+0 records in
16777216+0 records out
17179869184 bytes (17 GB) copied, 180.596 s, 95.1 MB/s
sarangb@nuxbox:~$ sudo chmod 600 /mnt/16gb.swap
sarangb@nuxbox:~$

Once we have file allocated and intialized, create a swap volume out of it and then activate it.

1
2
3
4
5
6
7
sarangb@nuxbox:~$ 
sarangb@nuxbox:~$ sudo mkswap /mnt/16gb.swap 
Setting up swapspace version 1, size = 16777212 KiB
no label, UUID=24419a0b-5cfb-451f-b7ab-e7d9eac00475
sarangb@nuxbox:~$ 
sarangb@nuxbox:~$ sudo swapon /mnt/16gb.swap
sarangb@nuxbox:~$ 

If things go well, there won’t be an error on shell and you check the results from System Monitor or /proc/meminfo output:

1
2
3
4
5
sarangb@nuxbox:~$
sarangb@nuxbox:~$ cat /proc/meminfo | grep SwapTotal
SwapTotal:      20869112 kB
sarangb@nuxbox:~$ 
sarangb@nuxbox:~$

Or alternatively (see 19.9 GiB Swap Size):

So far all of this session only, for it to be made permanent: /etc/fstab needs to be tweaked. I opened up /etc/fstab vim, or any other text editor, and added an entry for 16gb.swap

/etc/fstab

That’s it.