DevOpsDevOps

How to Increase Swap Space Size on a Linux Server

Dec 06, 2023 · Updated: Jan 25, 2024 · by Tim Kamanin

Note: This tip should work on most Linux-based servers, such as Ubuntu, Debian, OpenSUSE, Fedora, and CoreOS.

A swap space is very handy when our server is running at the limits of its memory. Often, especially on VPS, the swap space file size is very small. You can check the size of the swap by running the following command:

free -m

This command should display output like:

              total        used        free      shared  buff/cache avail
Mem:           3944        1548        1172         110        1223     2026
Swap:          6655           0        6655

As you can see, in my example, the swap file size is 6GB, which is sufficient for this case. I've just extended it from a mere 512MB.

Here’s how to increase the swap space file size:

  1. Turn off all running swap processes with the following command (please note, it can take a while):

    sudo swapoff -a
    

  2. Resize the swap file to your desired value. In my case, it was 6GB:

    sudo fallocate -l 6G /swapfile
    

    Regarding the best file size for swap:

    It's recommended for swap space to be twice the size of RAM if the RAM amount is below 2GB. If the RAM amount is higher, the swap size should be the size of RAM plus 2GB. I have 4GB of RAM on the server, so I set it to 6GB.

  3. Ensure the swap file has the correct permissions:

    sudo chmod 600 /swapfile
    

  4. Inform the system where the swap file is:

    sudo mkswap /swapfile
    

  5. Activate the swap:

    sudo swapon /swapfile
    

  6. Make the swap persist on server restarts by adding the following line at the end of /etc/fstab:

    /swapfile swap swap sw 0 0
    

And that's it! You've now extended the available memory space on your server for free.

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates