Chapter 1 · Lesson 15 of 19
Server basics

Add swap space on Ubuntu

Swap is disk space the kernel uses as overflow memory when RAM is full, which can stop small servers from killing processes.

By the end you will

Add a 2 GB swap file to an Ubuntu server and make it survive reboots.

Time
14 min
Level
Beginner
Check
4 questions
You need
  • An Ubuntu server with sudo access
  • A few GB of free disk space

To add swap space on Ubuntu, you create a file, format it with mkswap, enable it with swapon and list it in /etc/fstab. A small server with 1 GB of RAM runs fine until a build, a database import or a traffic spike pushes memory past the limit. Without swap, the kernel’s out-of-memory killer ends a process, often your database or app, with no warning. A swap file gives the kernel a place to move rarely used memory pages so the busy ones can stay in RAM.

How it works#

Memory is split into pages. When RAM fills up, the kernel can write pages that have not been used recently to swap on disk and reuse the RAM. If a program needs that page again, the kernel reads it back. That read is far slower than RAM, which is why heavy swapping makes a server feel frozen.

So swap does two things in practice:

  • It gives you headroom for short spikes, so a brief peak does not kill a process.
  • It lets the kernel push idle pages out, which can leave more RAM for file caching.

It does not make a memory-hungry app fast. If free -h shows swap in constant use and the machine is slow, the real fix is more RAM or a smaller workload.

Swap can be a partition or a file. A file is easier on a cloud server because you do not repartition anything. The kernel has three requirements: the file must be on a filesystem that supports it, be readable only by root, and be formatted with mkswap. The swappiness setting (0 to 100, with 60 as the usual default) controls how eagerly the kernel uses swap.

Step 1: Check current swap#

bash
swapon --show
free -h

What you should see: if swapon --show prints nothing, there is no swap, and free -h shows 0B on the Swap: row. If it already lists an entry, you may not need more. Also check free disk space with df -h /.

Step 2: Create the file#

This example makes a 2 GB file at /swapfile:

bash
sudo fallocate -l 2G /swapfile

-l 2G sets the length. What you should see: no output. If fallocate fails on your filesystem, use this instead, which writes every block and takes a bit longer:

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

Here bs=1M count=2048 means 2048 blocks of 1 MiB.

Step 3: Lock down permissions#

Only root should read swap, since it can contain memory contents (see Linux file permissions explained):

bash
sudo chmod 600 /swapfile

What you should see: no output. Verify with ls -lh /swapfile, which should start with -rw-------.

Step 4: Format and enable it#

Warning: mkswap overwrites the target. Make sure the path is your new swap file and not an existing file or disk.

bash
sudo mkswap /swapfile
sudo swapon /swapfile

What you should see: mkswap prints Setting up swapspace with the size and a UUID. swapon prints nothing when it works.

Step 5: Make it permanent#

Back up fstab, then add one line:

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

The fields are file, mount point (none for swap), type, options and two dump/check flags. What you should see: the line printed back by tee. A typo in /etc/fstab can cause boot problems, so check it with cat /etc/fstab.

Check it worked#

bash
swapon --show
free -h

swapon --show should list /swapfile with type file and the size you chose. free -h should show the same total on the Swap: row. Reboot and run the commands again to confirm it persists. To test the fstab line without rebooting, run sudo swapoff /swapfile and then sudo swapon -a, which enables everything listed in fstab.

Edge cases and gotchas#

  • Some filesystems need extra care. Btrfs and ZFS do not treat a plain fallocate file like ext4 does. On Btrfs, a swap file has special requirements, so follow the filesystem’s own documentation rather than this lesson.
  • A sparse file triggers a “holes” error. If swapon says the swapfile has holes, fallocate produced a file with unallocated blocks. Remove it and recreate it with dd.
  • Swap can already exist. Some images ship with a swap file such as /swap.img or a swap partition. Adding a second one wastes disk. Check step 1 first.
  • Low disk space is a real risk. A 2 GB swap file on a 10 GB disk takes a fifth of it. Docker images and logs can fill the rest, so leave room.
  • Container-style hosts may refuse swap. On virtualisation that shares the host kernel, swapon can fail with a permission or operation error. That is a host limit, not a mistake in your commands.
  • Swappiness is a trade-off. Lower values make the kernel prefer RAM and use swap later. Set it for the current boot with sudo sysctl vm.swappiness=10. To make it persistent, put vm.swappiness=10 in a file under /etc/sysctl.d/.
  • A swap file is not a fix for a leak. If a process grows without limit, swap only delays the crash and slows the machine meanwhile.

Troubleshooting#

SymptomLikely causeFix
swapon: /swapfile: insecure permissions 0644, 0600 suggested.File readable by othersRun sudo chmod 600 /swapfile
fallocate failed: Operation not supportedFilesystem does not support fallocateCreate the file with dd instead
No space left on deviceDisk too full for the sizePick a smaller size or free space (df -h /)
swapon: /swapfile: swapon failed: Invalid argumentFile not formatted, or it has holesRun mkswap on it, or recreate it with dd
Swap gone after rebootfstab line missing or mistypedRe-check the line in /etc/fstab, then sudo swapon -a
Server is slow with swap in useThe workload needs more RAMCheck free -h and top, reduce load or use a bigger server
swapon: /swapfile: read swap header failedThe file was never formatted with mkswap, or is truncatedRun sudo mkswap /swapfile on it, or recreate the file
Swap is listed but free -h shows 0B used and the app still diesThe process hit a per-container or per-service memory limitCheck cgroup or Docker memory limits, swap does not raise them
The server boots slowly after a bad fstab lineThe line has a typoBoot the console, fix /etc/fstab from the .bak copy

To remove swap later, run sudo swapoff /swapfile, delete the fstab line, then sudo rm /swapfile.

Real-world scenario#

A 1 GB server runs a Node app and a Postgres container. Every few days the app disappears. dmesg shows Out of memory: Killed process and the name of the app.

You run free -h and see Swap: 0B. You create a 2 GB /swapfile, run chmod 600, mkswap and swapon, then add the line to /etc/fstab. swapon --show lists the file.

The next traffic spike pushes memory over the limit, but the kernel moves idle pages to disk instead of killing a process. The app slows for a minute and recovers. Weeks later free -h still shows swap in use, which tells you the real fix is a bigger plan, and swap bought you the time to decide.

Quick reference#

TaskCommand
Show swapswapon --show and free -h
Createsudo fallocate -l 2G /swapfile
Lock downsudo chmod 600 /swapfile
Format and enablesudo mkswap /swapfile && sudo swapon /swapfile
Persist/swapfile none swap sw 0 0 in /etc/fstab
Removesudo swapoff /swapfile, delete the fstab line, sudo rm /swapfile

Security and safety notes#

  • Check the path before mkswap; it erases whatever it is pointed at.
  • Back up /etc/fstab before editing it, because a broken line can slow or stop booting.

Next#

Move files to and from the server with Copy files with scp and rsync.

Check what you learned4 questions
1Why run chmod 600 on the swap file?
2What makes the swap file come back after a reboot?
3What can go wrong with mkswap?
4swapon says the swapfile has holes. Which fix does the lesson suggest?

Frequently asked questions

How big should the swap file be?

A common starting point is about the same size as RAM on small servers, less on large ones. Pick a size that fits your free disk space.

Is swap a replacement for more RAM?

No. Disk is much slower than memory, so heavy swapping makes a server crawl. Swap is a safety net, not extra speed.

Why did my app get killed even though I have swap?

Swap only delays the problem. If memory and swap are both used up, the kernel's out-of-memory killer ends a process. Check dmesg for Out of memory messages and consider a bigger server or lower memory limits.

Can I add swap on any VPS?

Most full virtual machines allow it. Some container-style hosts do not let you create swap inside the guest, and the swapon command then fails. Ask your provider if you hit that.

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios