Tutorial

How To Add Swap Space on Ubuntu 20.04

Published on May 4, 2020
English
How To Add Swap Space on Ubuntu 20.04
Not using Ubuntu 20.04?Choose a different version or distribution.
Ubuntu 20.04

Introduction

One way to guard against out-of-memory errors in applications is to add some swap space to your server. In this guide, we will cover how to add a swap file to an Ubuntu 20.04 server.

What is Swap?

Swap is a portion of hard drive storage that has been set aside for the operating system to temporarily store data that it can no longer hold in RAM. This lets you increase the amount of information that your server can keep in its working memory, with some caveats. The swap space on the hard drive will be used mainly when there is no longer sufficient space in RAM to hold in-use application data.

The information written to disk will be significantly slower than information kept in RAM, but the operating system will prefer to keep running application data in memory and use swap for the older data. Overall, having swap space as a fallback for when your system’s RAM is depleted can be a good safety net against out-of-memory exceptions on systems with non-SSD storage available.

Step 1 – Checking the System for Swap Information

Before we begin, we can check if the system already has some swap space available. It is possible to have multiple swap files or swap partitions, but generally one should be enough.

We can see if the system has any configured swap by typing:

  1. sudo swapon --show

If you don’t get back any output, this means your system does not have swap space available currently.

You can verify that there is no active swap using the free utility:

  1. free -h
Output
total used free shared buff/cache available Mem: 981Mi 122Mi 647Mi 0.0Ki 211Mi 714Mi Swap: 0B 0B 0B

As you can see in the Swap row of the output, no swap is active on the system.

Step 2 – Checking Available Space on the Hard Drive Partition

Before we create our swap file, we’ll check our current disk usage to make sure we have enough space. Do this by entering:

  1. df -h
Output
Filesystem Size Used Avail Use% Mounted on udev 474M 0 474M 0% /dev tmpfs 99M 932K 98M 1% /run /dev/vda1 25G 1.4G 23G 7% / tmpfs 491M 0 491M 0% /dev/shm tmpfs 5.0M 0 5.0M 0% /run/lock tmpfs 491M 0 491M 0% /sys/fs/cgroup /dev/vda15 105M 3.9M 101M 4% /boot/efi /dev/loop0 55M 55M 0 100% /snap/core18/1705 /dev/loop1 69M 69M 0 100% /snap/lxd/14804 /dev/loop2 28M 28M 0 100% /snap/snapd/7264 tmpfs 99M 0 99M 0% /run/user/1000

The device with / in the Mounted on column is our disk in this case. We have plenty of space available in this example (only 1.4G used). Your usage will probably be different.

Although there are many opinions about the appropriate size of a swap space, it really depends on your personal preferences and your application requirements. Generally, an amount equal to or double the amount of RAM on your system is a good starting point. Another good rule of thumb is that anything over 4G of swap is probably unnecessary if you are just using it as a RAM fallback.

Step 3 – Creating a Swap File

Now that we know our available hard drive space, we can create a swap file on our filesystem. We will allocate a file of the size that we want called swapfile in our root (/) directory.

The best way of creating a swap file is with the fallocate program. This command instantly creates a file of the specified size.

Since the server in our example has 1G of RAM, we will create a 1G file in this guide. Adjust this to meet the needs of your own server:

  1. sudo fallocate -l 1G /swapfile

We can verify that the correct amount of space was reserved by typing:

  1. ls -lh /swapfile
  1. -rw-r--r-- 1 root root 1.0G Apr 25 11:14 /swapfile

Our file has been created with the correct amount of space set aside.

Step 4 – Enabling the Swap File

Now that we have a file of the correct size available, we need to actually turn this into swap space.

First, we need to lock down the permissions of the file so that only users with root privileges can read the contents. This prevents normal users from being able to access the file, which would have significant security implications.

Make the file only accessible to root by typing:

  1. sudo chmod 600 /swapfile

Verify the permissions change by typing:

  1. ls -lh /swapfile
Output
-rw------- 1 root root 1.0G Apr 25 11:14 /swapfile

As you can see, only the root user has the read and write flags enabled.

We can now mark the file as swap space by typing:

  1. sudo mkswap /swapfile
Output
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes) no label, UUID=6e965805-2ab9-450f-aed6-577e74089dbf

After marking the file, we can enable the swap file, allowing our system to start using it:

  1. sudo swapon /swapfile

Verify that the swap is available by typing:

  1. sudo swapon --show
Output
NAME TYPE SIZE USED PRIO /swapfile file 1024M 0B -2

We can check the output of the free utility again to corroborate our findings:

  1. free -h
Output
total used free shared buff/cache available Mem: 981Mi 123Mi 644Mi 0.0Ki 213Mi 714Mi Swap: 1.0Gi 0B 1.0Gi

Our swap has been set up successfully and our operating system will begin to use it as necessary.

Step 5 – Making the Swap File Permanent

Our recent changes have enabled the swap file for the current session. However, if we reboot, the server will not retain the swap settings automatically. We can change this by adding the swap file to our /etc/fstab file.

Back up the /etc/fstab file in case anything goes wrong:

  1. sudo cp /etc/fstab /etc/fstab.bak

Add the swap file information to the end of your /etc/fstab file by typing:

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

Next we’ll review some settings we can update to tune our swap space.

Step 6 – Tuning your Swap Settings

There are a few options that you can configure that will have an impact on your system’s performance when dealing with swap.

Adjusting the Swappiness Property

The swappiness parameter configures how often your system swaps data out of RAM to the swap space. This is a value between 0 and 100 that represents a percentage.

With values close to zero, the kernel will not swap data to the disk unless absolutely necessary. Remember, interactions with the swap file are “expensive” in that they take a lot longer than interactions with RAM and they can cause a significant reduction in performance. Telling the system not to rely on the swap much will generally make your system faster.

Values that are closer to 100 will try to put more data into swap in an effort to keep more RAM space free. Depending on your applications’ memory profile or what you are using your server for, this might be better in some cases.

We can see the current swappiness value by typing:

  1. cat /proc/sys/vm/swappiness
Output
60

For a Desktop, a swappiness setting of 60 is not a bad value. For a server, you might want to move it closer to 0.

We can set the swappiness to a different value by using the sysctl command.

For instance, to set the swappiness to 10, we could type:

  1. sudo sysctl vm.swappiness=10
Output
vm.swappiness = 10

This setting will persist until the next reboot. We can set this value automatically at restart by adding the line to our /etc/sysctl.conf file:

  1. sudo nano /etc/sysctl.conf

At the bottom, you can add:

/etc/sysctl.conf
vm.swappiness=10

Save and close the file when you are finished.

Adjusting the Cache Pressure Setting

Another related value that you might want to modify is the vfs_cache_pressure. This setting configures how much the system will choose to cache inode and dentry information over other data.

Basically, this is access data about the filesystem. This is generally very costly to look up and very frequently requested, so it’s an excellent thing for your system to cache. You can see the current value by querying the proc filesystem again:

  1. cat /proc/sys/vm/vfs_cache_pressure
Output
100

As it is currently configured, our system removes inode information from the cache too quickly. We can set this to a more conservative setting like 50 by typing:

  1. sudo sysctl vm.vfs_cache_pressure=50
Output
vm.vfs_cache_pressure = 50

Again, this is only valid for our current session. We can change that by adding it to our configuration file like we did with our swappiness setting:

  1. sudo nano /etc/sysctl.conf

At the bottom, add the line that specifies your new value:

/etc/sysctl.conf
vm.vfs_cache_pressure=50

Save and close the file when you are finished.

Conclusion

Following the steps in this guide will give you some breathing room in cases that would otherwise lead to out-of-memory exceptions. Swap space can be incredibly useful in avoiding some of these common problems.

If you are running into OOM (out of memory) errors, or if you find that your system is unable to use the applications you need, the best solution is to optimize your application configurations or upgrade your server.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Brian Boucheron
Brian Boucheron
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

I installed Ubuntu Server 20.04 LTS and during the installation I didn’t see that the swap partition would be mounted, I think it’s because the concept in Ubuntu is different from Slackware: in Ubuntu it is a swap file while in Slackware it is a partition. This tutorial explains how to make the swap file, I saw here that Ubuntu Server 20.04 LTS already came with a file called swap.img at the root, I didn’t need to create it.

KFSys
Site Moderator
Site Moderator badge
February 9, 2025

Heya,

That’s a bit weird. Usually you’ll need to create the SWAP file as you need to give it space and add it to your fstab.

ZFS “fallocate” doesn’t work on ZFS partition. Why is that?

root@PC:/home/user# sudo fallocate -l 8G /swapfile fallocate: fallocate failed: Operation not supported root@PC:/home/user#

Do you think you can add an option within this article, for ZFS systems? Or that won’t happen? Thanx

KFSys
Site Moderator
Site Moderator badge
December 8, 2023

Heya,

The fallocate command doesn’t work on ZFS file systems because ZFS does not support pre-allocating space in the way fallocate requires. Instead, for creating a sparse file on ZFS, you can use the truncate command. This alternative approach is cross-filesystem compatible and suitable for use with ZFS.

KFSys
Site Moderator
Site Moderator badge
February 9, 2025

Here is an example of how to achieve this:

You can create a sparse file (which does not immediately allocate space) using:

truncate -s 2G /swapfile

This will create a logical 2GB file, but the disk space will not be fully allocated until data is written.

Another example would be using DD.

If you want to create a fully allocated file, use:

dd if=/dev/zero of=/swapfile bs=1M count=8192

This method will write actual zero bytes to the file, ensuring it is fully allocated.

  • bs=1M → Block size of 1MB
  • count=8192 → Creates 8192 blocks (8GB total)

After creating the file, you can enable it as a swap file:

  1. Set the correct permissions:
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo "/swapfile none swap sw 0 0" | sudo tee -a /etc/fstab
  • truncate is best if you want a sparse file (space-efficient).
  • dd is better if you want the file fully allocated (no surprises with storage availability).
  • mkswap and swapon work the same as on other filesystems.

thanks :)

Can you list here the procedure how to remove the swap file as well

  1. sudo swapoff -v /swapfile
  2. Remove entry /swapfile none swap sw 0 0 from /etc/fstab
  3. Remove swapfile with command sudo rm /swapfile
KFSys
Site Moderator
Site Moderator badge
December 8, 2023

Removing a Swap File:

  • First, deactivate the swap space using the command sudo swapoff -v /swapfile.
  • Then, remove the swap file entry from /etc/fstab using a text editor.
  • Finally, delete the actual swap file with sudo rm /swapfile.

I had problem with sudo swapon /swapfile -> swapon: /swapfile: swapon failed: Invalid argument

Problem is solved with using sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576 instead of sudo fallocate -l 1G /swapfile

Interesting that you’ve got the “invalid argument”. The fallocate command creates a sparse file, hence the error, but somehow I did not get that error. Strange. In any event, it’s not a good idea to use a sparse file as a swap file.

The dd ... command is a great replacement, though.

KFSys
Site Moderator
Site Moderator badge
July 28, 2024

This usually happens if the swap file wasn’t created or configured correctly. As mentioned the DD command works and it’s a great way to go around the problem.

Thank You, help me in my Ubuntu 20.04.1 LTS Cinnamon Remix Desktop, to create swapfile.

Soo

“Don’t do this, but here’s how to do this”

hmmm

KFSys
Site Moderator
Site Moderator badge
February 9, 2025

Heya,

Using a swapfile (or swap partition) on an SSD can lead to potential issues due to the way SSDs handle writes and erasures.

  • SSDs have a limited number of write cycles per cell (though modern SSDs have improved durability).
  • Swap usage involves frequent writes, which can accelerate SSD wear and reduce its lifespan.
  • Unlike RAM, which can handle millions of writes without degradation, SSD cells have a finite number of Program/Erase (P/E) cycles.
  • SSDs are much faster than HDDs, but they are still significantly slower than RAM.
  • If your system is constantly swapping, performance will degrade because the SSD cannot match RAM speeds.
  • This is especially problematic for applications requiring low-latency memory access (e.g., databases, real-time processing).

So on all digital ocean plans it is not possible to activate swap, right?

As they all have SSDs

Wondered the same thing. Working with a smaller Droplet with just 1GB ram and adding a swap file could help a lot, but since Digital Ocean uses SSD… we are basically told this is a bad idea because it can cause faster hardware degradation over time…

You actually can create a swap file and use it just fine. They just don’t like it too much…

What I think they should offer is a HDD just for swap space. They could have a 10Tb HDD and let each VM in that machine use X Gb (where X should probably be about the same as your RAM). Then we wouldn’t destroy their precious SSD and we would not lose that functionality.

KFSys
Site Moderator
Site Moderator badge
July 28, 2024

Heya,

It’s possible to create a swap file and use it as SWAP. It’s just not as recommend for hardware purposes however you creating SWAP on your Droplet is not forbidden or you won’t be stopped as well.

KFSys
Site Moderator
Site Moderator badge
February 9, 2025

If you are wondering why that is here is some info on it:

  • SSDs are much faster than HDDs, but they are still significantly slower than RAM.
  • If your system is constantly swapping, performance will degrade because the SSD cannot match RAM speeds.
  • This is especially problematic for applications requiring low-latency memory access (e.g., databases, real-time processing).
  • SSDs have a limited number of write cycles per cell (though modern SSDs have improved durability).
  • Swap usage involves frequent writes, which can accelerate SSD wear and reduce its lifespan.
  • Unlike RAM, which can handle millions of writes without degradation, SSD cells have a finite number of Program/Erase (P/E) cycles.
KFSys
Site Moderator
Site Moderator badge
December 8, 2023

Heya,

It’s possible to create a swap file and use it as SWAP. It’s just not as recommend for hardware purposes however you creating SWAP on your Droplet is not forbidden or you won’t be stopped as well.

All in all, the key takeaway is that while you can enable swap space on your droplets, you should be aware of the potential impact on SSD lifespan and consider whether the benefits outweigh the risks in your specific use case.

Good Article!

nice clear write-up. Thank you. A couple questions.

1 How would I remove it?

2 How to change permissions?

swapon: /swapfile: insecure permissions 0644, 0600 suggested.

use chmod 600 /swapfile to change the permisisons to the recommended. You can use the swapoff command to turn off swap, then remove the entry in /etc/fstab as well

KFSys
Site Moderator
Site Moderator badge
December 8, 2023

Heya,

To address your questions:

  1. Removing a Swap File:

    • First, deactivate the swap space using the command sudo swapoff -v /swapfile.
    • Then, remove the swap file entry from /etc/fstab using a text editor.
    • Finally, delete the actual swap file with sudo rm /swapfile.
  2. Changing Permissions of a Swap File:

    • To address the permissions warning, change the swap file’s permissions to the suggested 0600. This can be done with the command sudo chmod 0600 /swapfile.
    • After changing the permissions, you can make the swap file active again using sudo swapon /swapfile.

These steps should help you manage your swap file effectively on Ubuntu 20.04. Remember, it’s important to have root privileges to perform these operations.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.