Create Swap File on Cloud Linux Server to Prevent Out of Memory

When a Linux server runs out of memory, some programs such as MariaDB/MySQL will shutdown automatically. To prevent out of memory (OOM) problem, we can create a swap partition or swap file so as to expand the memory. In this tutorial, we’re going to look at how to create a swap file on Linux server with small memory.

First, let me explain some background information.

Swap Space

When you are installing Linux on a desktop computer or a server, one of the considerations is how much swap space it’s going to use. Swap space is a kind of virtual memory. Linux divides RAM into pages. When the physical RAM starts to fill up, Linux can swap out some pages in the RAM to the swap space on disk. To calculate how much virtual memory your system has, simple add physical RAM and swap space.

Swap space in Linux can be a swap partition, swap file or a combination of them. In windows, it’s just a page file stored in C drive. Normally Linux installers such as Ubuntu Ubiquity and CentOS Anaconda try to set aside a swap partition when installing the system.

To check your Linux system’s swap space, use the swapon --show command. You may need to use sudo.

swapon --show

swapon command

We can get the following information.

  • how many swap partitions or swap files are in our Linux system
  • the size of each swap device
  • how much swap space is being used
  • the priority of each swap device

Priority controls which swap device is used first. Swap devices with a higher number are used before swap devices with lower number.

Create a Swap File

On a cloud Linux server, you may have only one partition for the root file system. In this case, you have no way of creating another partition and format it as swap partition.  In stead we can create a swap file in the root file system.

First, we use fallocate command to create a file. For example, create a file named swapfile with 512M capacity in root file system:

sudo fallocate -l 512M /swapfile

To create a 1G file:

sudo fallocate -l 1G /swapfile

Then make sure only root can read and write to it.

sudo chmod 600 /swapfile

Format it to swap:

sudo mkswap /swapfile

Output:

Setting up swapspace version 1, size = 524284 KiB
no label, UUID=h32b3e10-0779-4865-9ea0-6e2af8f3kea9

Enable the swap file

sudo swapon /swapfile

Now you can see that it’s enabled with swapon --show command.

admin@server:~$ sudo swapon --show
NAME      TYPE  SIZE  USED  PRIO
/swapfile file  512M  132K  -1

To make Linux automatically mount this swap file when booting up, add this line to /etc/fstab file.

/swapfile  none  swap  defaults  0  0

swap file

Please note that you need to delimit each column with Tab key.

Swappiness

Swappiness is a Linux kernel parameter that controls how often Linux swap out idle processes to the swap space on your hard drive.

The value of swappiness is between 0 ~ 100. Lower value means Linux will use swap space less whereas higher value causes Linux to use swap space more often. The default value on Ubuntu is 60 which means when your computer uses up 40% of physical RAM, Linux kernel begins swapping.

You can use the following command to check the current value.

cat /proc/sys/vm/swappiness

It’s recommended to set a low value for swappiness so that Linux kernel will use as much physical RAM as possible. Edit the /etc/sysctl.d/99-sysctl.conf file.

sudo nano /etc/sysctl.d/99-sysctl.conf

At the end of this file, append the following line.

vm.swappiness=5

This tells Linux kernel to only use swap space when 95% or more of physical RAM is used up. You can also set the value to 0, so Linux will only use swap space when all physical memory is used up.

vm.swappiness=0

Save and close the file. Then run the following command to apply the changes.

sudo sysctl -p

Note that the htop utility doesn’t report accurately the amount of free RAM on Linux. It doesn’t count shared memory, buffer and cache. To show the accurate amount of free RAM on Linux server, use the free -m command.

How to Disable Swap File on Debian & Ubuntu

Swap space can make your server slower and it can wear out the SSD on your server much faster than you think. If you need better performance, it’s a good idea to upgrade the physical RAM, then disable swap space. To disable swap file, install the dphys-swapfile package.

sudo apt install dphys-swapfile

Then edit the configuration file.

sudo nano /etc/dphys-swapfile

Find the following line.

#CONF_SWAPFILE=/var/swap

By default, the swap file is set to /var/swap. Remove the # character to uncomment this line and change its value to /swapfile.

CONF_SWAPFILE=/swapfile

Next, run the following command, which will fetch all content in the swap file back into the physical RAM, then disable the swap file.

sudo dphys-swapfile swapoff

Now you can delete the swap file to reclaim disk space.

sudo dphys-swapfile uninstall

It’s recommended to disable the dphys-swapfile service, so it won’t automatically create a swap file at boot time.

sudo systemctl disable dphys-swapfile

If you can’t use the above method to disable swap space, then you can try the following command, which will disable all swap devices and files (as found in /proc/swaps or /etc/fstab).

sudo swapoff -a

swapoff will fetch all content in the swap space back into the physical RAM, then disable the swap space.

Disable Swap Space Automatically

If your server has enough RAM, then you might want to prevent any services from creating swap space. You can create a Cron job, so it will disable swap space periodically.

sudo crontab -e

Add the following line at the end of the crontab file.

* * * * * /sbin/swapoff -a

This will run swapoff every minute. Save and close the file.

Wrapping Up

I hope this tutorial helped you use swap space on Linux server. You may also want to read:

As always, if you found this post useful, then subscribe to our free newsletter to get new tutorials 🙂

Rate this tutorial
[Total: 2 Average: 5]

5 Responses to “Create Swap File on Cloud Linux Server to Prevent Out of Memory

  • Thanks for the tutorial Xiao. Very helpful with out of memory exceptions when installing MySQL with only 512 MB of ram!

  • Mysterion
    3 years ago

    Thanks for the detailed guide!

  • Dear all, I am trying to create a Create Swap File on Cloud Linux Server to Prevent Out of Memory. In the first step I write:

    sudo fallocate -l 2G / swapfile

    It returned

    (base) enri @ enri-260-p100ns: ~ $ sudo fallocate -l 2G / swapfile
    fallocate: fallocate has failed: The text file is busy
    (base) enri @ enri-260-p100ns: ~ $
    

    What can be the cause of this error? – I will appreciate help. Kind regards

  • Dear All. I have verified that I have a swap partition

    (base) enri@enri-260-p100ns:~$ sudo swapon --show 
    [sudo] contraseña para enri:         
    NAME      TYPE SIZE  USED PRIO
    /swapfile file   2G 23,5M   -2
    (base) enri@enri-260-p100ns:~$ 
    

    What could be the next step). Thanks

  • Dear all. Finally I hav made the nest.

    (base) enri@enri-260-p100ns:~$ sudo swapoff -a
    (base) enri@enri-260-p100ns:~$ sudo fallocate -l 8G /swapfile
    (base) enri@enri-260-p100ns:~$ sudo chmod 600 /swapfile
    (base) enri@enri-260-p100ns:~$ sudo mkswap /swapfile
    mkswap: /swapfile: atención: se destruye la firma antigua swap.
    Configurando espacio de intercambio versión 1, tamaño = 8 GiB (8589930496 bytes)
    sin etiqueta, UUID=a971f8e6-f663-4826-b29e-f787c6c66100
    (base) enri@enri-260-p100ns:~$ sudo swapon /swapfile
    (base) enri@enri-260-p100ns:~$ swapon --show
    NAME      TYPE SIZE USED PRIO
    /swapfile file   8G   0B   -2
    (base) enri@enri-260-p100ns:~$ /etd/fstab file
    bash: /etd/fstab: No existe el archivo o el directorio
    (base) enri@enri-260-p100ns:~$ echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab 
    /swapfile none swap sw 0 0
    (base) enri@enri-260-p100ns:~$ 
    

    I’m going to test the result. If you apreciated any problem, I apreciate your help. Best regards

Leave a Comment

  • Comments with links are moderated by admin before published.
  • Your email address will not be published.
  • Use <pre> ... </pre> HTML tag to quote the output from your terminal/console.
  • Please use the community (https://community.linuxbabe.com) for questions unrelated to this article.
  • I don't have time to answer every question. Making a donation would incentivize me to spend more time answering questions.

The maximum upload file size: 2 MB. You can upload: image. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here