Using Linux, there are two ways to increase swap size. The first is with a partition created when installing the system, and the second is with a file in our file system, commonly named swapfile. An example in which we might need to add swap is in the case of 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.
Table of Contents
Increase swap space with a file
For Ubuntu users or for any distribution that does not allow us to use 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, with the dd
command.
sudo dd if=/dev/zero of=/swap1 bs=1024 count=1000000
The output will look like this:
~$ 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 swap is about 1 GB, for a 2 GB we change the parameter count to 2000000 and for a 4 GB one we change it to 4000000. The amount is not exact in this case regarding measurement systems. To calculate the exact size of the file, use the method found on the source page at the end of this article.
As recommended by the command we will use to convert the file, we must give 0600 permissions to the file.
sudo chmod 0600 /swap1
Now convert the file to swap type with:
sudo mkswap /swap1
Then we start it by activating it:
sudo swapon /swap1
Swap verification
To verify that the swap file is being used in the system, run:
free -h
Command output:
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 htop
and top
the amount of swap available to verify. Ideally, check with this command before adding swap and right after adding, to get a clear picture of whether our system is using the new swap.
Permanent swap
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. But at the same time, it is an advantage. If we have the possibility to use a good portion of our SSD drive as swap, our system will thank us.
This way, if we are executing by mistake 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 best of all, without restarting our system.
Source: web3us.com