Report this

What is the reason for this report?

How To Add Swap Space on Ubuntu

Updated on March 12, 2026
English

Not using Ubuntu 20.04?
Choose a different version or distribution.
Ubuntu 20.04
How To Add Swap Space on Ubuntu

Introduction

When a server runs out of RAM, the kernel can kill processes (OOM kills), crash applications, or refuse new connections. Swap space gives the system a disk-backed fallback so it can move less-used data out of RAM and keep the system running under memory pressure. On cloud VPS instances with fixed RAM, adding swap is a standard way to reduce the risk of out-of-memory failures without immediately upgrading the droplet.

This guide shows how to add swap on Ubuntu using a swap file: create the file, enable it, make it persistent across reboots, and tune kernel settings. All steps work without a reboot and apply to Ubuntu 22.04 and later versions.

EOL notice: Ubuntu 20.04 LTS reached the end of standard support in April 2025 and no longer receives standard security updates by default. Extended updates are available via Ubuntu Pro/ESM; see the official Ubuntu release and support lifecycle for details. The commands in this guide remain valid and are fully compatible with Ubuntu 22.04 LTS and Ubuntu 24.04 LTS.

Key Takeaways

  • Check first: Use swapon --show and free -h to see if swap is already active before adding more.
  • Use a swap file, not a partition: On Ubuntu (and on cloud VPS like DigitalOcean Droplets), a swap file is the right choice: easier to create and resize, no repartitioning.
  • Size by RAM: For most servers, match swap to RAM up to a point (e.g., 1x RAM for 2–8 GB RAM; at least 4 GB for 8–64 GB). Avoid oversized swap on small-RAM systems.
  • Make it persistent: Add an entry to /etc/fstab so swap is enabled after reboot; otherwise it is only active until the next restart.
  • Tune for servers: Lower vm.swappiness (e.g., 10) so the kernel prefers RAM over swap; add both vm.swappiness and vm.vfs_cache_pressure to /etc/sysctl.conf if you want changes to survive reboots.
  • Swap is a safety net: If the server regularly hits swap, the right fix is to upgrade RAM, not to add more swap.

What is Swap?

Swap is disk space the kernel uses as overflow when RAM is full. Data moved to swap is much slower to access than RAM, so the kernel keeps active data in memory and uses swap mainly for less-used pages. That tradeoff lets the system avoid some out-of-memory situations: instead of killing processes, it can push older data to disk and free RAM for current work. On systems with SSD storage, swap file performance is typically acceptable for this role.

When the kernel cannot find enough free RAM for a new allocation, its page replacement logic selects less recently used memory pages and writes them to swap; when that data is needed again, a page fault occurs and the kernel must read the page back from disk, which is noticeably slower than accessing RAM. If this back-and-forth happens continuously, you see thrashing in practice: the system feels sluggish or briefly unresponsive, load average spikes, and disk activity stays high even when there is no obvious workload. On SSD-backed servers such as DigitalOcean Droplets, occasional swap use is usually tolerable because random reads are relatively fast, but on HDD-backed systems even moderate swap use causes severe latency because seek times are orders of magnitude slower than RAM access.

Swap File vs. Swap Partition

You can provide swap either as a dedicated partition or as a file on an existing filesystem. For Ubuntu servers, especially on cloud VPS, a swap file is usually the better option.

Aspect Swap file Swap partition
Creation Create a file with fallocate or dd; no repartitioning Requires free disk space and partition changes (e.g., fdisk, LVM)
Resize Disable, delete, recreate at new size, re-enable Resizing is possible but more involved (LVM/partitions)
Cloud VPS Works on DigitalOcean Droplets and similar; no extra volumes Not recommended: block devices are often fixed at creation
Performance Comparable to a swap partition for SSD-backed servers No advantage on SSD; marginally faster on spinning disks only

Use a swap file unless you have a specific reason (e.g., legacy or policy) to use a partition.

Cloud VPS: On DigitalOcean Droplets and similar cloud VPS, use a swap file on the root filesystem. Swap partitions are not recommended because block layout is fixed at droplet creation and resizing is impractical.

Choose swap size based on how much RAM the server has. The following table gives practical starting points:

RAM Recommended swap
Less than 2 GB 2× RAM
2 GB – 8 GB 1× RAM
8 GB – 64 GB Minimum 4 GB (more if you run memory-heavy or bursty workloads)
Above 64 GB At least 4 GB; add more only if you have a known need (e.g., hibernation or specific apps)

These are guidelines. Adjust for your workload: light services may need less; databases or build jobs may benefit from slightly more. Avoid making swap many times larger than RAM on small systems; it can mask the need for a RAM upgrade and worsen performance if the system starts thrashing.

Step 1 – Checking the System for Swap Information

Check whether the system already has swap. Multiple swap areas are possible, but one is usually enough.

Run:

  1. sudo swapon --show

No output means no swap is currently active.

Confirm with:

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

The Swap row shows total, used, and free. Zero across the row means no active swap.

Step 2 – Checking Available Space on the Hard Drive

Ensure the filesystem has enough free space for the swap file. Use the mount point that will hold the file (usually /):

  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 ...

The row where Mounted on is / is your root filesystem. In this example, 23G is available. Pick a swap size that fits (see the table above) and leaves room for logs and updates.

Step 3 – Creating a Swap File

Create a file of the desired size. This example uses 1G; replace with the size that matches your RAM and the recommendations above (e.g., 2G, 4G).

Preferred method: fallocate creates the file quickly:

  1. sudo fallocate -l 1G /swapfile

Verify the file size:

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

If fallocate fails: On some filesystems (Btrfs, NFS), use dd instead:

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

Replace count=1024 with the number of MiB you need (e.g., 2048 for 2 GB). Then continue with Step 4.

Step 4 – Enabling the Swap File

Restrict the file so only root can read it (swap can contain sensitive data from memory):

  1. sudo chmod 600 /swapfile

Verify:

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

Format the file as swap and turn it on:

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

Confirm swap is active:

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

The PRIO value of -2 is the default kernel-assigned priority; if you add multiple swap areas, higher priority values are used first.

  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

Swap is now in use for the current boot only. The next step makes it persistent.

Step 5 – Making the Swap File Permanent

Without an /etc/fstab entry, the system will not enable this swap after a reboot.

Back up /etc/fstab:

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

Append the swap entry:

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

Verify the line was added:

  1. grep swapfile /etc/fstab
Output
/swapfile none swap sw 0 0

The fields are: device path, mount point (none for swap), filesystem type (swap), mount options (sw enables the swap area at boot), and two zeros that disable dump and fsck for swap.

After the next reboot, swap will be activated automatically. You can test by rebooting and running sudo swapon --show again.

Step 6 – Tuning Swap and Cache Settings

Two kernel parameters affect how aggressively the system uses swap and how it treats filesystem cache. Tuning them can improve server behavior under memory pressure.

Adjusting Swappiness

vm.swappiness (0–100) controls how readily the kernel moves memory pages to swap. Higher values mean more swapping; lower values keep more data in RAM. Default on Ubuntu is 60, which is often too high for servers that should prefer RAM.

Workload Recommended swappiness Why
Web server (Nginx, Apache) 10 Consistent response times matter more than RAM efficiency; avoid disk latency on request handling
Database server (MySQL, PostgreSQL) 10 Databases manage their own buffer pools; kernel swapping database pages causes severe query latency
Build server / CI runner 10–20 Build jobs spike RAM briefly; light swapping is acceptable but thrashing during compilation is costly
Desktop / interactive session 60 Default is appropriate; interactive use benefits from keeping more data accessible at the cost of some swap

Check the current value:

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

Set it for the current session (e.g., 10):

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

To keep this across reboots, add it to /etc/sysctl.conf:

  1. echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

A value of 10 is a common choice for servers: the kernel will still use swap when needed but will not push data to disk as eagerly, reducing unnecessary I/O. For more on system-wide tuning, see Tuning Linux for Performance.

Adjusting Cache Pressure

vm.vfs_cache_pressure influences how long the kernel keeps inode and dentry (filesystem metadata) in cache. Default is 100; lowering it (e.g., to 50) makes the kernel retain this metadata longer, which can help I/O-heavy workloads.

Check the current value:

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

Set for the current session:

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

To persist, add to /etc/sysctl.conf:

  1. echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf

Persistence: Both vm.swappiness and vm.vfs_cache_pressure must be in /etc/sysctl.conf (or in a file under /etc/sysctl.d/) to apply after reboot. Setting them only with sysctl affects the current boot only.

Verify your sysctl entries:

  1. grep -E 'swappiness|vfs_cache_pressure' /etc/sysctl.conf
Output
vm.swappiness=10 vm.vfs_cache_pressure=50

Duplicate entries: Running these commands more than once will add duplicate lines to /etc/sysctl.conf. Before re-running, check with grep -E 'swappiness|vfs_cache_pressure' /etc/sysctl.conf and remove any duplicate lines manually.

Resizing or Removing Swap

To change swap size or remove it, disable swap, remove the file (or old file), then recreate if needed and re-enable.

1. Turn off swap:

  1. sudo swapoff /swapfile

2. Remove the swap file:

  1. sudo rm /swapfile

3. Remove the line for /swapfile from /etc/fstab (edit with nano or sed so the system does not try to enable a missing file at boot):

  1. sudo sed -i.bak -E '/^[[:space:]]*\/swapfile([[:space:]]|$)/d' /etc/fstab

Verify the line is gone:

  1. grep swapfile /etc/fstab

No output is expected.

4. To add swap again at a different size: Repeat Step 2 (check disk space), Step 3 (create a new file with the desired size, using fallocate or dd if needed), Step 4 (chmod, mkswap, swapon), and Step 5 (add the new /swapfile entry to /etc/fstab if you removed it).

After resizing, confirm with sudo swapon --show and free -h.

Troubleshooting

fallocate fails or swap acts wrong (e.g., on Btrfs/NFS)
Use dd to create the file instead: sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress (use count=2048 for 2G, etc.). Then run sudo chmod 600 /swapfile, sudo mkswap /swapfile, and sudo swapon /swapfile.

Swap is not active after reboot
Check that /etc/fstab has exactly one line for your swap file (e.g., /swapfile none swap sw 0 0) and that the path matches the real file. Run sudo swapon -a to activate all swap devices listed in fstab and see if errors appear. Fix or re-add the fstab line if the path is wrong or the file was moved.

System still hits OOM even with swap
Swap does not prevent OOM kills when both RAM and swap are exhausted. The kernel will still kill processes once there is no more free memory. If you see OOM in logs despite swap, the fix is to add more RAM or reduce memory use, not only to add more swap. Use tools like atop to inspect memory and swap usage over time.

High swap usage and slow performance
Heavy use of swap means the system is repeatedly reading and writing disk, which is slow. Check with vmstat 1 (look at si/so columns for swap in/out). If swap is used heavily under normal load, the machine is undersized for that workload. Prefer upgrading RAM over adding more swap; more swap does not fix thrashing. For compute-intensive workloads such as model training, see GPU options for fine-tuning to evaluate whether a GPU Droplet is a better fit than adding more swap.

FAQ

How much swap space should I add on Ubuntu?
Use a size that matches your RAM tier: for example, 2× RAM if under 2 GB RAM, 1× RAM for 2–8 GB, and at least 4 GB for 8–64 GB. Adjust for your applications; avoid very large swap on small-RAM systems.

Is a swap file better than a swap partition?
On Ubuntu and on cloud VPS (e.g., DigitalOcean Droplets), a swap file is usually better: easier to create and resize, no repartitioning, and similar performance on SSDs. Use a partition only if you have a specific requirement.

Can I add swap without rebooting?
Yes. Create the file, run mkswap and swapon, and add the entry to /etc/fstab. Swap is active immediately and will be re-enabled after reboot.

How do I check if swap is active on Ubuntu?
Run sudo swapon --show to list active swap; run free -h and look at the Swap row for total, used, and free.

What is the default swappiness value in Ubuntu?
The default is 60. For servers, a lower value such as 10 is often better so the kernel relies less on swap.

Can too much swap slow down my system?
Yes. If the system frequently uses swap, disk I/O increases and response times suffer. Large swap can also hide the need for more RAM. If you see high swap usage (e.g., via vmstat or free), consider upgrading RAM.

How do I remove swap space in Ubuntu?
Run sudo swapoff /swapfile, remove the file with sudo rm /swapfile, and delete the /swapfile line from /etc/fstab so the system does not try to enable it at boot.

Conclusion

Adding a swap file on Ubuntu gives the kernel a disk-backed buffer when RAM is tight, which can prevent or delay OOM kills and process crashes. Follow the steps above to create the file, enable it, add it to /etc/fstab, and optionally tune vm.swappiness and vm.vfs_cache_pressure for your server. If the server regularly relies on swap under normal load, the right fix is to upgrade RAM rather than to add more swap; swap is a safety net, not a substitute for sufficient memory. For workloads involving GPU-accelerated tasks, see the CUDA performance tuning workflow for environment-specific guidance.

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
Author
See author profile

Senior Technical Writer at DigitalOcean

Vinayak Baranwal
Vinayak Baranwal
Editor
Technical Writer II
See author profile

Building future-ready infrastructure with Linux, Cloud, and DevOps. Full Stack Developer & System Administrator. Technical Writer @ DigitalOcean | GitHub Contributor | Passionate about Docker, PostgreSQL, and Open Source | Exploring NLP & AI-TensorFlow | Nailed over 50+ deployments across production environments.

Still looking for an answer?

Was this helpful?


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.

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

thanks :)

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

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

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

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

As they all have SSDs

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.
Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

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.