Back to Blog

How to Add a Swap File on Linux

Create a Linux swap file with fallocate, mkswap and swapon, keep it after reboots via fstab, tune swappiness and learn when you need more RAM instead.

Nodesty Team6 min readServers
The words Linux Swap with fallocate, mkswap and swappiness on a dark Nodesty background

When a Linux server runs out of memory, the kernel's OOM killer steps in and kills a process, often the one using the most memory, such as your database or game server. A swap file gives the server some breathing room for those moments: when RAM fills up, rarely used memory pages are moved to disk instead of an application being killed.

Many cloud images and small VPS installs come without any swap. This guide covers checking whether you have swap, creating a swap file, keeping it after reboots, tuning swappiness and, just as important, when swap helps and when you actually need more RAM.

Do you already have swap?

After connecting to your server over SSH, run:

free -h
swapon --show

If the Swap row in free -h shows 0B and swapon --show prints nothing, there's no swap on the server. If you see a line, swap is already active; you can still follow the resizing section below.

How big should the swap file be?

Swap on a server is a safety net, not extra memory. A rough guide:

Server RAMSuggested swap
1–2 GBEqual to RAM
4–8 GB2–4 GB
8 GB+2–4 GB is plenty

Make sure you have enough free disk space before you start; check with df -h. If the disk is already tight, see our Linux disk full guide first.

Creating the swap file

The steps below create a 2 GB swap file at /swapfile. Change 2G to the size you want.

1. Create the file:

sudo fallocate -l 2G /swapfile

fallocate reserves the space instantly. If it fails with an error such as fallocate failed: Operation not supported, or swapon later complains that the file has holes, create the file with dd instead; it's slower because it actually writes zeros:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

2. Restrict the permissions so that only root can read the file. Swap can contain anything that was in memory, including passwords and keys:

sudo chmod 600 /swapfile

3. Format the file as swap and turn it on:

sudo mkswap /swapfile
sudo swapon /swapfile

4. Check:

swapon --show
free -h

You should now see /swapfile with the size you chose and a non-zero Swap row.

On Btrfs, a plain swap file doesn't work this way because of copy-on-write. On recent versions of btrfs-progs, use sudo btrfs filesystem mkswapfile --size 2G /swapfile instead of steps 1 to 3. Ubuntu, Debian and AlmaLinux use ext4 or XFS by default, where the steps above work as they are.

Keeping swap after a reboot

swapon only lasts until the next reboot. To turn the swap file on at boot, add it to /etc/fstab. Take a backup of the file first; a broken fstab can stop the server from booting:

sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

To check that the file is valid before you reboot:

sudo findmnt --verify

Tuning swappiness and vfs_cache_pressure

vm.swappiness controls how eagerly the kernel moves memory to swap. It ranges from 0 to 100 (up to 200 on newer kernels) and defaults to 60, which suits desktops. On a server you usually want applications to stay in RAM for as long as possible and swap to be used only when memory is really running out, so 10 is a common choice.

vm.vfs_cache_pressure controls how quickly the kernel drops its cache of file and directory information. The default is 100; a value of 50 keeps this cache longer, which helps servers that work with a lot of files.

To see the current values:

cat /proc/sys/vm/swappiness
cat /proc/sys/vm/vfs_cache_pressure

To make the change permanent, create a file under /etc/sysctl.d/:

sudo nano /etc/sysctl.d/99-swap.conf
vm.swappiness = 10
vm.vfs_cache_pressure = 50

Apply it without rebooting:

sudo sysctl --system

Avoid setting swappiness to 0; on modern kernels this practically disables swap until memory is completely full, and the OOM killer can step in before swap is used at all.

Resizing the swap file

To make the swap file bigger or smaller, turn it off, recreate it and turn it back on:

sudo swapoff /swapfile
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

swapoff moves everything in swap back into RAM, so check with free -h that there's enough free memory first. Your fstab line stays the same because the file name hasn't changed. If fallocate doesn't shrink the file, delete it with sudo rm /swapfile after swapoff and create it again.

Removing the swap file

sudo swapoff /swapfile
sudo rm /swapfile

Then delete the /swapfile none swap sw 0 0 line from /etc/fstab. If you leave the line in place, you'll see an error at boot.

When swap helps, and when you need more RAM

Swap helps when:

  • Memory usage spikes briefly, for example during a package upgrade, a backup or a build.
  • There are services that load once and then sit idle; their memory can be moved to disk to make room for active applications.
  • You want time to react before the OOM killer kills a process.

Swap doesn't help when the server is constantly short of memory. Swap lives on disk; even on NVMe it's many times slower than RAM. If free -h shows swap usage that keeps growing and the si/so columns in vmstat 1 are constantly non-zero, the server is spending its time moving memory back and forth. That's why it feels sluggish; our Why is my server slow? guide covers how to read these signs.

To see whether the OOM killer has already killed a process:

sudo dmesg -T | grep -i "killed process"
sudo journalctl -k | grep -i "out of memory"

Game servers and databases

Swap isn't a replacement for RAM on game servers and databases. When part of a Minecraft server's Java heap ends up in swap, garbage collection has to read it back from disk and players notice it as lag spikes. The same goes for a database's buffer pool: queries that should be answered from memory start waiting on the disk.

On these servers, keep a small swap file only as a safety net and size the memory settings so they fit in RAM. For example, set the Minecraft server's -Xmx value well below the server's RAM and leave room for the operating system; we cover this in detail in our Minecraft server lag guide. If the application still doesn't fit, the fix is more RAM, not more swap.

Keep an eye on memory and swap

Add memory and swap usage to your monitoring so you know before the OOM killer acts; we cover the options in our Server monitoring guide. Commands such as free, vmstat and htop are also in our Linux commands guide.

Swap and RAM on Nodesty servers

Nodesty AMD Ryzen 9 9950X VPS and AMD EPYC 7763 VPS plans are virtualized with KVM and come with NVMe disks and full root access, so you can create a swap file and tune swappiness exactly as described in this guide. Daily backups are free on VPS plans and are kept for 7 days. If your server keeps living in swap, moving to a plan with more RAM is the lasting fix; the 9950X plans suit game servers with their high single-core speed, while the EPYC plans offer plenty of RAM for databases and many services.

Frequently Asked Questions

How much swap should a server have?

For most servers 1 to 4 GB is enough. On a server with 1 or 2 GB of RAM, swap equal to the RAM is a sensible start; on servers with 8 GB of RAM or more, 2 to 4 GB is usually plenty. Swap on a server is a safety net for short memory spikes, not extra memory, so making it very large doesn't help.

Is a swap file slower than a swap partition?

On modern kernels and file systems such as ext4 and XFS, the difference is negligible. A swap file is much easier to create, resize and remove than a partition, which is why it's the usual choice on virtual servers.

Does swap fix a lack of RAM?

No. Swap lives on disk and is many times slower than RAM. It keeps applications from being killed during a short memory spike, but if the server uses swap all the time, it slows down noticeably. The real fix is to reduce the application's memory usage or move to a plan with more RAM.

What swappiness value should I use?

On servers, a value of 10 is a common choice; the kernel then keeps applications in RAM for as long as possible and only uses swap when memory is really running out. The default value of 60 suits desktops better. Set the value in a file under /etc/sysctl.d so it survives reboots.

Should I use swap on a game server or database server?

A small swap file as a safety net is fine, but the game server or database itself shouldn't be living in swap. When a Minecraft server's Java heap or a database's buffer pool ends up on disk, lag spikes and slow queries follow. Size the memory settings below the server's RAM and get more RAM if that isn't enough.

How do I remove a swap file?

Turn the swap off with sudo swapoff /swapfile, delete the /swapfile line from /etc/fstab and then delete the file with sudo rm /swapfile. Before turning it off, check with free -h that there's enough free RAM to take over what is currently in swap.

Nodesty

About the author

Nodesty Team · Infrastructure & Support

The Nodesty team runs our servers, network and DDoS protection day to day and answers customer support requests around the clock. These guides come from that work.

Related articles

Launch your server now.

Build, scale, and conquer without limits on Nodesty's premium infrastructure.

                                                                                                                                                                                                                            
                                                                                                                                                                                                                            
                                                                                                                                                                                                                            
                                                                                                                             ············································                                                   
                                                ··································································································..........···························                                     
                                       ················..........................................................................................................................··············                             
                                  ·············.................::::::::::::::::::::::::::::::::::::::::::::::....................:::::::::::::::::::::::::::::::::::::::................···········                        
                             ············................:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::............·········                     
                         ············.................:::::::::::::::::::::::::::::::::::::::::::::::::::------------::::::::::::::::::::::::::::::----------------:::::::::::::::::::::..........········                  
                    ············......................::::::::::::::::::::::::::::::::::::------------------------------------------------------------------------------------:::::::::::::.........········                
                ··········.............................................::::::::::::::::::-------------==========================================-----------------------------------:::::::::::........·······               
             ········..................:.....................................::::::::::--------=======+++++++++++++++++++++++++++++++++++++=========================------------------::::::::::.......·······              
           ······.........::::::::::::::::::::................................:::::::-----=====++++xxxxxx**************************xxxxxxxxx++++++++++++++===================------------::::::::.......·······             
          ·····.......:::::::::::::::::::::::::::.............................:::::----===+++xxx****%%%%&&&&&&#############&&&&&&&%%%%%*******xxxxxxxx++++++++++++++==============----------:::::::......······             
         ····......::::::::-------------:::::::::::..........................::::---===+++xx***%%%&&&####@@@@@@@@@@@@@@@@@@@@@@@@####&&&&&%%%%*******xxxxxxxxx+++++++++++++===========--------::::::......·····             
        ····.....:::::::--------------------:::::::::.......................::::---===++xxx**%%&&&###@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@###&&&&%%%%%********xxxxxxxxxxx++++++++++++========------::::::.....······            
        ····.....:::::--------------------------::::::::....................::::---===++xx***%%&&&####@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@###&&&&&%%%%%**********xxxxxxxxxxxxx+++++++++=======------:::::.....·····            
        ····....::::::-------=============---------:::::::::................:::::---===+++xx***%%%&&&#####@@@@@@@@@@@@@@@@@@@@@@@@@#####&&&&&%%%%%%*************xxxxxxxxxxxxxx+++++++++======-----:::::....·····            
         ····....:::::-------================---------:::::::::...............:::::----===++++xxx***%%%%&&&&&&#################&&&&&&%%%%%%%*******************xxxxxxxxxxxxxxxxx++++++++======----:::::....·····            
         ·····....:::::--------=================---------::::::::::..............:::::::-----====+++++xxxxxx**************************xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx++++++++=====-----::::....·····            
          ·····.....:::::--------=================----------:::::::::::.................:::::::::-------=============++++++++++++++++++++++++++++++++++++xxxxxxxxxxxxxxxxxxxxxxx++++++++======-----::::....·····            
            ·····.....:::::::----------===========-------------::::::::::::.........................::::::::::::::::::------------------=============+++++++++++++++++++++++++++++++++=======-----::::.....·····            
              ······......:::::::---------------------------------:::::::::::::........................................:::::::::::::::-----------============+++++++++++++++++++++========------:::::.....·····             
                 ······........:::::::::---------------------------:::::::::::::::::...........................................:::::::::::::------------=============================--------::::::.....······              
                    ·········.........:::::::::::::::-------------::::::::::::::::::::::::.......................................::::::::::::::::--------------------------------------::::::::......·······                
                          ··········............::::::::::::::::::::::::::::::::::::::::::::::::::................................::::::::::::::::::::::::::-------------:::::::::::::::.........········                   
                                  ············..................:::::::::::::::::::::::::::::::::::::::::::.........................:::::::::::::::::::::::::::::::::::::................···········                        
                                             ················.............................................................................................................·················                                 
                                                           ······················................................................................···························                                                
                                                                               ·········································································