Enabling virtual memory in the form of a swapfile can be useful when trying to avoid running out of memory doing rare peaks in memory usage on a system—even when the system already has enough physical memory. This is because, when a Linux system runs out of memory, it might completely freeze up and/or shut down important processes to free memory.
This might result in /var/log/syslog containing messages like:
... Out of memory: Killed process ...
Enabling a swap file on a Linux system can be done by first using the dd command to format a swapfile, then mkswap and swapon to make and enable the swap. An easy way to format the swapfile is by using the "count" option with "bs"; bs is the blocksize, while count specifies the number of times the blocksize should be repeated.
Enter the following commands to create and enable your swap file:
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress sudo mkswap /swapfile sudo swapon /swapfile
Why we may want to create a swap file
Website owners will often not make enough money on ads to cover their hosting expenses, and therefor we might want to use the smallest possible virtual servers to host our websites—often this is just a typical LAMP stack (Linux + Apache + MySQL + PHP).
With cloud providers such as AWS or Azure, it is possible to deploy servers of a variety of different sizes. The smallest typically has no more than 512-1024 Megabytes of RAM, and often times this is not enough to secure optimal operation.
Enabling a swap file and/or changing the configuration of different services to use less memory may still allow us to use these smaller instances.
Enabling swap might increase costs
When using a cloud hosting provider, such as AWS and Azure, enabling a swap file might result in increased costs due to extra IOPS (Input/Output Operations Per Second), but this might depend on storage type. For certain storage types, there should be no additional charges for read/write operations, but performance might slow down once you reach a certain limit.
Note. You should examine the documentation of your hosting provider and storage type to learn the exact details that applies in your case.
As a step towards keeping costs down we can apply certain modifications to our server configuration to keep memory use below the available physical memory. For example, there are settings that can be changed for both MySQL and PHP to lower memory consumption.