In Linux there are two ways to have swap. The first is with a partition created when installing the system, and the second is with a file in our file system. An example in which we might need to add swap is in the case of virtual servers or virtual machines, since they do not have swap by default and when we have to run an application like composer things get quite complicated. There are many scenarios of this type and databases, PHP, Apache, among others, may be involved, in which our system can be rendered useless due to not having enough swap, so let's start.
For Ubuntu users or for any distribution that does not allow using root directly we have to prepend sudo in all the commands.
This applies to almost any distribution, first we create a file full of zeros.
dd if=/dev/zero of=/swap1 bs=1024 count=1000000
~$ dd if=/dev/zero of=/swap1 bs=1024 count=1000000 1000000+0 records in 1000000+0 records out 1024000000 bytes (1.0 GB, 977 MiB) copied, 1.9816 s, 517 MB/s
This is about 1GB, for a 2GB we change count to 2000000 and for a 4GB one we change it to 4000000. The amount is not exact in this case, to calculate the exact size of the file use the method found on the source page at the end of this article.
Now convert the file to swap type:
Then we start it:
To verify that the swap file is being used run:
total used free shared buff/cache available Mem: 1.9Gi 400Mi 82Mi 93Mi 1.5Gi 1.3Gi Swap: 2.0Gi 192Mi 1.8Gi
In the part that says "Swap:" in "total" you must say the amount we assign or even more. We can also check with
top the amount of swap available to verify.
To activate the swap at each restart of the system edit /etc/fstab with
nano or the editor of our preference as "root" and we add the following line referring to the swap file created earlier:
/swap1 swap swap defaults 0 0
We can create as many files as we want, but we must not forget that they take up disk space, and if we talk about space in a VPS it is usually limited by the fact that they use SSD disks.
This way if by mistake we are executing
composer update and we do not have so much RAM we can use swap as long as we have space on our disk available, and the best of all without restarting our system.