How to add swap space to Linux
One of the most common operations is to add swap space to a Linux machine, there are two ways, the first one is to create a swap partition…
One of the most common operations is to add swap space to a Linux machine, there are two ways, the first one is to create a swap partition and the second one to create a swap file, in this article we will see how we can create a swap file and then mount it in our system to be used.
Create a directory for the swap file
Its a good practice to create a directory where the swap files will be placed
$ sudo mkdir /swapCreate the swap file
Second step is to create a swap file and specify its size, to do this we will use the dd command to create an empty file of 4GB to be used as swap file
$ sudo dd if=/dev/zero of=/swap/swap4G bs=1024 count=4000000The output should be something like this
4000000+0 records in
4000000+0 records out
4096000000 bytes (4.1 GB, 3.8 GiB) copied, 32.9246 s, 124 MB/sNow we need to do some rights tunning, it needs to be readable and writable from the root user only
$ sudo chmod 600 /swap/swap4GFormat the swap file
Next step is to format the swap file as swap!
$ sudo mkswap /swap/swap4GThe output should be similar to this
Setting up swapspace version 1, size = 3.8 GiB (4095995904 bytes)
no label, UUID=7addfa3c-d6f8-4641-a8c2-b1a90c49c48eEnabling swap
To enable swap use the swaponcommand
$ sudo swapon /swap/swap4GWe can verify that the swap space is activated with the -s parameter of the swapon command
$ sudo swapon -s
Filename Type Size Used Priority
/swap/swap4G file 3999996 0 -2Mount swap on boot
Using the swapon command will not persist swap file activation between reboots, to do this we need to append it to /etc/fstab
/swap/swap4G swap swap defaults 0 0We can test that the fstab entry works by using
$ mount -aIt should not produce any output if everything is ok!
Conclusion
We saw how easy is to create a swap file, format it and finally mount it, just be careful and use a swap size that fills your needs and remember: swap is not a replacement for actual RAM