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…

How to add swap space to Linux
Photo by Hans Eiskonen on Unsplash
Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…

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 /swap

Create 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=4000000

The 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/s

Now we need to do some rights tunning, it needs to be readable and writable from the root user only

$ sudo chmod 600 /swap/swap4G

Format the swap file

Next step is to format the swap file as swap!

$ sudo mkswap /swap/swap4G

The output should be similar to this

Setting up swapspace version 1, size = 3.8 GiB (4095995904 bytes) 
no label, UUID=7addfa3c-d6f8-4641-a8c2-b1a90c49c48e

Enabling swap

To enable swap use the swaponcommand

$ sudo swapon /swap/swap4G

We 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       -2

Mount 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 0

We can test that the fstab entry works by using

$ mount -a

It 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

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…